我正在Laravel/VueJS/InertiaJS堆栈中试用Vue3的Composition API。
我在Vue2中使用这个堆栈时经常使用的一种做法是,有一个路由返回Vue页面组件(例如Invoices.Vue),然后在
created()
回调时,我会触发对另一个端点的axios调用来获取实际数据。
我现在正在尝试在Vue3中复制类似的方法,使用类似的组合API
export default {
components: {Loader, PageBase},
props: {
fetch_url: {
required: true,
type: String,
}
},
setup(props) {
const loading = ref(false)
const state = reactive({
invoices: getInvoices(),
selectedInvoices: [],
});
async function getInvoices() {
loading.value = true;
return await axios.get(props.fetch_url).then(response => {
return response.data.data;
}).finally(() => {
loading.value = false;
})
}
function handleSelectionChange(selection) {
state.selectedInvoices = selection;
}
return {
loading,
state,
handleSelectionChange,
}
}
}
然而,这不断给我提供建议,而不是返回的实际数据。
这样改变确实有效:
export default {
components: {Loader, PageBase},
props: {
fetch_url: {
required: true,
type: String,
}
},
setup(props) {
const loading = ref(false)
const state = reactive({
invoices: [],
selectedInvoices: [],
});
axios.get(props.fetch_url).then(response => {
state.invoices = response.data.data;
}).finally(() => {
loading.value = false;
})
function handleSelectionChange(selection) {
state.selectedInvoices = selection;
}
return {
loading,
state,
handleSelectionChange,
}
}
}
不过我想使用函数,这样我就可以重复使用它进行过滤等。
很好奇别人是怎么做的。
我一直在谷歌上搜索,但似乎找不到相关的文档。
我们非常欢迎所有反馈。