-1

在我的应用程序中,我有一个 Vuex 4 商店和一个 Vue 3 Composition Apisetup()方法。

在商店操作中,我使用 axios 进行 api 调用以获取账单支付列表。

getAllBills操作不直接存在于我的Store.js文件中,它作为一个模块存在。

 getAllBills({ commit }) {
            BillApiCalls.getBills().then(res => {
                commit('GET_ALL_BILLS', res.data)
            }).catch(error => console.log(error))
        },

然后在我的 Bill.vue 文件中,我有setup()方法并尝试访问要在整个 Bill.vue 文件中使用的数据。

setup () {
    //Vuex store
    const store = useStore();
    const billPayments =  store.dispatch('payment/getAllBills').then(res => console.log(res));
}

如果我从上面检查控制台.then() res返回未定义。如果我.then()billPayments声明中删除并执行以下操作:

console.log(billPayments)

在控制台中我得到

Promise {<pending>}.

当前商店:

import { bill } from './modules/bill.module';

const store = createStore({
    modules: {
        bill
    }
});

端点正在工作,如果我使用 Postman,我的所有数据都会按预期返回,但我无法弄清楚如何使用带有组合 API 的调度操作访问该数据。

Vuex 4 文档没有提到如何实际解决访问要在同一组件中使用的数据的承诺。

4

1 回答 1

0

一个动作通常不应该返回它所作用的数据,数据是状态的一部分,应该在那里访问;这是另一个答案显示的内容:

await store.dispatch('payment/getAllBills')
console.log(store.state.payment.bills);

该操作不会链接承诺,因此无法正确使用。它应该是:

return BillApiCalls.getBills()...

或者更喜欢async..await与 Promise 一起使用,以避免使用原始 Promise 可能犯的一些常见错误。

于 2021-08-24T15:13:03.810 回答