Vue2中this.$store.dispatch正常但...mapActions调用无效求助
问题分析与解决方案
你的问题核心不是生命周期时机问题,而是在created钩子中仅引用了映射后的addStage方法,未执行调用。
问题代码中的错误点
在组件的created钩子中,你写的是:
this.addStage;
这只是获取了方法的引用,并没有触发执行。而直接使用this.$store.dispatch('flowbuilder/addStage')时,是主动调用了dispatch方法,所以能正常触发action和mutation。
修正后的组件代码
<template> <div v-for="stage in getFlow.stages" :key="stage.id"> <flowstage v-for="step in stage.steps" :key="step.id"> <flowstep></flowstep> </flowstage> </div> </template> <script> import { mapGetters, mapActions } from 'vuex'; export default { name: 'flowbuildersub', created(){ // 修正:调用映射后的action方法 this.addStage(); console.log("added stage"); }, methods: { ...mapActions('flowbuilder', ['addStage']), }, computed: { ...mapGetters('flowbuilder', ['getFlow']), } } </script>
补充说明
created钩子完全适合用于组件初始化时调用Vuex action加载数据,不存在时机问题。- 映射后的
addStage方法本质是封装了this.$store.dispatch('flowbuilder/addStage')的调用,只要正确执行(加括号调用),就能和直接dispatch达到完全一致的效果。
其他代码验证(无需修改)
Store主文件:
import Vue from 'vue'; import Vuex from 'vuex'; import flowbuilder from './modules/flowbuilder.js'; Vue.use(Vuex); export default new Vuex.Store({ state: { error: null, loading: false, information: null }, getters: { getError(state) { return state.error; }, getInformation(state) { return state.information; }, getLoading(state) { return state.loading; }, }, mutations: { setInformation(state, payload) { state.information = payload }, setError(state, payload) { state.error = payload }, setLoading(state, payload) { state.loading = payload } }, modules: { flowbuilder } })
flowbuilder模块文件:
export const state = { flow: { id: Math.ceil(Math.random()*100000000)+Math.floor(Date.now() / 1000), name: null, description: null, modifiedBy: null, stages: [], }, }; export const getters = { getFlow(state) { return state.flow; }, getStages(state) { return state.flow.stages; }, }; export const actions = { addStage({ commit }) { let defaultStep = { id: 1, type: "Assign", data: null, description: null, subStep: null, required: null, selected: true, }; let defaultStage = { id: 1, label: null, description: null, selected: false, steps: [ defaultStep ], }; console.log("made it here"); commit('ADDSTAGE', defaultStage); }, }; export const mutations = { ADDSTAGE(state, defaultStage) { state.flow.stages.push(defaultStage); console.log("added stage"); }, }; export default { namespaced: true, state, getters, actions, mutations };
内容的提问来源于stack exchange,提问作者supremesector
相关产品推荐
相关产品推荐

