【发布时间】:2022-01-05 02:14:29
【问题描述】:
我正在 Laravel/VueJS/InertiaJS 堆栈中试验 Vue3 的 Composition API。
我在 Vue2 中使用此堆栈经常使用的一种做法是有 1 个返回 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,
}
}
}
我想使用函数,所以我可以重新使用它进行过滤等。
非常想知道其他人是如何做到这一点的。 我一直在谷歌上搜索了一下,但似乎找不到相关的文档。
非常欢迎所有反馈。
【问题讨论】:
标签: vuejs3 vue-composition-api inertiajs