简体   繁体   中英

Mutation Doesn't Set Value in State

I set values with mutations , but it doesn't update values in state object. It creates new variables inside mutations object. IMG

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

I update a value with commit function. eg: 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);
          ...........
         });
      }

Isn't it supposed to update null values in state object instead of creating new variables in mutations object?

You seem to be misusing modules. I'll assume you aren't actually trying to use them. You also have unintended property nesting with your state import.

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

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