Vue3 Composition API结合Vuex4派发Action后如何获取返回数据
问题根因
- 你的Vuex Action没有返回Promise:当前
getAllBills方法仅内部调用了接口,但没有将接口请求的Promise向外返回,导致dispatch后的.then()无法拿到返回值。 - 模块命名映射错误:你在Store中注册的子模块名为
bill,但你派发Action时使用的路径是payment/getAllBills,命名空间不匹配,实际上没有触发到目标Action。 - 数据获取方式不符合Vuex设计规范:Vuex采用单向数据流设计,业务数据应该统一从State中获取响应式数据,而非从Action的返回值直接获取。
修改方案
第一步:修改子模块中的Action代码,返回Promise
getAllBills({ commit }) { // 新增return将接口Promise向外暴露 return BillApiCalls.getBills().then(res => { commit('GET_ALL_BILLS', res.data) // 若需要在dispatch的回调中直接拿到返回值,可在此处return对应数据 return res.data }).catch(error => { console.log(error) throw error // 抛出错误方便上层捕获处理 }) },
注意:如果你的bill子模块没有开启命名空间,需要在模块配置中新增namespaced: true才能用模块名/Action名的方式派发,不需要前缀的话可以省略该配置。
第二步:修改Bill.vue中setup的代码,从State取响应式数据
import { computed, onMounted } from 'vue' import { useStore } from 'vuex' setup () { const store = useStore() // 从State中取响应式的账单列表,注意字段名要和你Mutation里存入State的字段保持一致 const billPayments = computed(() => store.state.bill.billList) // 派发Action,路径和注册的模块名保持一致 onMounted(async () => { const res = await store.dispatch('bill/getAllBills') console.log(res) // 此时可以正常拿到接口返回值 }) // 将响应式数据返回给模板使用 return { billPayments } }
修改后模板中可以直接使用billPayments渲染数据,接口请求完成后数据会自动更新。
内容的提问来源于stack exchange,提问作者CodeConnoisseur
相关产品推荐
相关产品推荐

