简体   繁体   中英

Why Vuex doesn't update state inside module?

Using Vue 2. My state isn't updated inside module. I created simplified example of my code. Store config:

import Vue from "vue";
import Vuex, { StoreOptions } from "vuex";
import users from "@/store/modules/users";
import test from "@/store/modules/test";
import { vuexfireMutations } from "vuexfire";
import { RootState } from "@/store/types";

Vue.use(Vuex);

const store: StoreOptions<RootState> = {
  state: {
    version: 0
  },
  mutations: {
    ...vuexfireMutations
  },
  actions: {},
  modules: { users, /* other modules */ test },
  strict: process.env.NODE_ENV !== "production"
};

export default new Vuex.Store<RootState>(store);

Individual module (test.ts):

import { RootState, TestState } from "@/store/types";
import { ActionTree, GetterTree, Module, MutationTree } from "vuex";

const getters: GetterTree<TestState, RootState> = {};

const mutations: MutationTree<TestState> = {
  SET_TEST(state, nextState: TestState) {
    console.log("current", state); //shows correct current state
    // let's say nextState is following: { test: "Hi!" }
    console.log("next", nextState); //show correct next state 
    state = { ...state, ...nextState, loaded: true };
  },
};

const actions: ActionTree<TestState, RootState> = {
  setTest({ commit }, payload: TestState) {
    commit("SET_TEST", payload);
  }
};

const test: Module<TestState, RootState> = {
  namespaced: true,
  state: {
    loaded: false
  },
  getters,
  mutations,
  actions
};

export default test;

After dispatching setTest action, everything goes properly through vuex except mutation. Next action payload is exactly what I want but my state for that module still shows test: { loaded: false } , but should be: test: { test: "Hi,": loaded: true"}

You should not assign to the state - because you will replace a reactive Object with a non-reactive one.

Instead, create a key/property inside the state - and mutate its value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM