【问题标题】:Access data from dispatched action using Vuex 4 and Vue 3 Composition API使用 Vuex 4 和 Vue 3 组合 API 从调度的操作中访问数据
【发布时间】:2021-10-24 18:36:03
【问题描述】:

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

在 stores 操作中,我使用 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 返回未定义。如果我从 billPayments 声明中删除 .then() 并执行以下操作:

console.log(billPayments)

在控制台中我得到

Promise {<pending>}.

当前商店:

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

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

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

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

【问题讨论】:

    标签: vue.js vue-composition-api vuex4


    【解决方案1】:

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

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

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

    return BillApiCalls.getBills()...
    

    或者更喜欢 async..await 与 promise 一起使用,以避免一些常见的错误,这些错误可能在原始 promise 中出现。

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 2020-05-28
      • 2021-07-14
      • 2019-08-16
      • 2021-05-23
      • 2018-04-25
      • 2020-11-22
      • 2021-06-24
      • 2021-09-27
      相关资源
      最近更新 更多