问题描述
是否可以在使用Option API的传统组件中导入和使用新的成分API?
这是我的情况:
// ComponentA.js
import { reactive } from '@vue/composition-api'
export default {
////////////////////////////////////////////////////////////////
setup() {
//////////////////////////////////////////////
// State
const state = reactive({
isSearching: false,searchText: '',isShowMoreResults: false,resultItems: []
})
//////////////////////////////////////////////
const search = async (searchText) => {
console.log("Searching... ",searchText)
}
//////////////////////////////////////////////
const clear = async () => {
console.log("Clear search")
}
//////////////////////////////////////////////
const nextResults = async () => {
console.log("Next Results")
}
////////////////////////////////////////////////////////////////
return {
state,search,clear,nextResults
}
}
}
我想在我的“ Option API”样式组件中使用它。 我该如何导入?
我尝试过此方法,但它不起作用。 导入工作正常,但我不知道如何调用设置方法并获取所有导出的字段:
import useComponentA from 'ComponentA.js'
let { state } = useComponentA()
解决方法
作为ComponentA.js编写的是组件本身。您返回了state
(将变成$data.state
)和3个函数search
,clear
和nextResults
,它们将成为组件上的方法。如果您现在想使用ComponentA,只需将其导入到像这样使用ComponentA的某些ComponentB中即可
// ComponentB
import ComponentA from 'ComponentA.js'
export default {
components: { ComponentA },// ...
}
如果仅使用Options API编写ComponentA,则它看起来像这样:
export default {
data() {
return {
isSearching: false,searchText: '',isShowMoreResults: false,resultItems: []
};
},methods: {
async search() {...},async clear() {...},async nextResults() {...}
}
}
在ComponentA的示例中,您实际上根本没有使用Options API。您可以可以像这样混合使用两种API:
// ComponentA.js
import { reactive } from '@vue/composition-api'
export default {
setup() {
const state = reactive({
isSearching: false,resultItems: []
})
return { state }
},async nextResults() {...}
}
}
IMO,仅当您具有某些逻辑完全属于该组件时,才可以混合使用API。例如,如果您有一些表单组件和用于处理该表单唯一的Submit事件的方法。尽管它足够新,但实际上并没有标准的约定或最佳实践。