Vue / Vuex - 不保存状态数据

时间:2017-10-24 08:18:37

标签: vuejs2 vuex

我制作了一个vuex模块来保持用户的数据状态。它看起来像这样:

import Vue from "vue";

export default {
  namespaced: true,
  state: {
    data: {},
    meta: {}
  },
  mutations: {
    setInitialUserData: function(user){
      state.data = user;
    },
    setUserMeta: function(meta){
      state.meta = meta;
    },
  },
  actions: {
    setInitialData: function({commit}, user){
      console.log(user);
      commit('setInitialUserData', user.user);
      commit('setUserMeta', user.userMeta);
    },
  },
  getters: {
    getUser: (state) => state.data,
    getUserMeta: (state) => state.meta
  }
}

我正在尝试在我的组件中保存登录数据,如下所示:

this.$backend.post('/user/login', null, payload)
      .then(response => {
        this.$store.dispatch('auth/login', response.data.token);
        this.$store.dispatch('user/setInitialData', response.data.user);
        //this.$router.push('intranet');
      })
      .catch(error => {
        //console.log(error);
      });
  }

我在这里得到的数据:

setInitialData: function({commit}, user){
      console.log(user);
      commit('setInitialUserData', user.user);
      commit('setUserMeta', user.userMeta);
    },
  }, 

看起来像这样:

    "user": {
        "name": "John Doe",
        "nice_name": "John",
        "login_name": "John",
        "email": "john@gmail.com"
    },
    "userMeta": {
        "department": "Administrasjon",
        "region": "Oslo",
        "industry": "Bane"
    },

但是,没有任何东西被保存到状态,在检查vuex状态时,我得到用户数据和用户元数据的空对象:

user:Object
data:Object (empty)
meta:Object (empty)

1 个答案:

答案 0 :(得分:3)

你没有将状态传递给你的变种者:

mutations: {
    setInitialUserData: function(state, user){
         state.data = user;
    },
    setUserMeta: function(state, meta){
        state.meta = meta;
    },
},