突变不会在状态中设置值

Mutation Doesn't Set Value in State

我使用 mutations 设置值,但它不会更新状态对象中的值。它在 mutations 对象中创建新变量。

mutations.js:

const mutations = {
  setUser(state, user) {
    state.user = user; // eslint-disable-line no-param-reassign
  },
  setToken(state, token) {
    state.token = token; // eslint-disable-line no-param-reassign
  },
  setAuthenticated(state, authenticated) {
    state.authenticated = authenticated; // eslint-disable-line
  },
};


export default {
  mutations,
};

state.js:

const state = {
  callingAPI: false,
  activeSidebar: true,
  searching: '',
  authenticated: null,
  user: null,
  token: null,
  userInfo: {
    messages: [],
    notifications: [],
    tasks: [],
  },
};

const getters = {
  isAuthenticated: (state) => { // eslint-disable-line
    return state.authenticated;
  },
  isActiveSidebar: (state) => { // eslint-disable-line
    return state.activeSidebar;
  },
};

export default {
  state,
  getters,
};

store.js:

import Vue from 'vue';
import Vuex from 'vuex';
import state from './state';
import mutations from './mutations';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    state,
    mutations,
  },
});

我用 commit 函数更新了一个值。例如:this.store.commit('setAuthenticated', true);

import { mapMutations } from 'vuex';
import store from '../store';

export default {
  computed: {
    ...mapMutations([
      'setAuthenticated',
      'setUser',
      'setToken',
    ]),
  },
  store,
  login(context, creds) {
    context.$http.post(LOGIN_URL, JSON.stringify(creds)).then(
      (response) => {
        if (response.status === 200) {
          const bodyText = response.bodyText.split('\n');
          const token = bodyText[0].split(' ');
          let redirect = bodyText[1];
          redirect = redirect.substring(redirect.indexOf('[') + 1, redirect.indexOf(']'));
          this.store.commit('setToken', token[1]);
          this.store.commit('setAuthenticated', true);
          ...........
         });
      }

难道不应该更新 state 对象中的空值而不是在 mutations 对象中创建新变量吗?

您似乎在滥用模块。我假设您实际上并没有尝试使用它们。您也有意外的 属性 与您的 state 导入嵌套。

store.js

import Vue from 'vue';
import Vuex from 'vuex';
import {state,getters} from './state';
import mutations from './mutations';

Vue.use(Vuex);

export default new Vuex.Store({
    state,
    getters,
    mutations,
});