【问题标题】:Mutation Doesn't Set Value in State突变不会在状态中设置值
【发布时间】:2018-04-23 02:51:57
【问题描述】:

我使用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对象中创建新变量吗?

【问题讨论】:

    标签: vue.js vuex mutation


    【解决方案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,
    });
    

    【讨论】:

    • 感谢您的回答。您的回答引导了我应该如何在 Vuex.Store() 中定义这些,而只需进行一些更改。
    猜你喜欢
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2018-10-05
    • 2020-11-29
    • 2020-06-05
    • 1970-01-01
    • 2020-09-10
    相关资源
    最近更新 更多