突变不在州内设定价值

时间:2017-11-09 23:17:36

标签: vue.js vuex mutation

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

mutation.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对象中创建新变量?

1 个答案:

答案 0 :(得分:1)

你好像在滥用模块。我假设你并没有真正尝试使用它们。您还使用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,
});