【问题标题】:Why Vuex doesn't update state inside module?为什么 Vuex 不更新模块内部的状态?
【发布时间】:2023-03-30 06:12:02
【问题描述】:

使用 Vue 2。我的状态未在模块内更新。我创建了我的代码的简化示例。 存储配置:

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);

单个模块(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;

在调度setTest 动作之后,除了突变之外,一切都通过 vuex 正常进行。下一个动作负载正是我想要的,但我对该模块的状态仍然显示test: { loaded: false },但应该是:test: { test: "Hi!", loaded: true"}

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    您应该不分配给state - 因为您将用非反应性对象替换反应性对象。

    相反,在 state 中创建一个键/属性 - 并改变它的值。

    【讨论】:

      猜你喜欢
      • 2021-10-05
      • 2021-06-19
      • 2016-12-13
      • 2017-08-01
      • 2021-11-03
      • 2020-11-23
      • 2020-12-22
      • 2021-12-20
      • 2023-03-16
      相关资源
      最近更新 更多