提交mutations之后,state的值没有发生变化

vuex相关代码(user.js)

let users = [
  {"username":"Lucy","password":"123456","login":false},
  {"username":"qweasd","password":"123456","login":false},
  {"username":"iopjkl","password":"123456","login":false}
];

const state = users[0] || '';

const mutations = {
  [types.GET_USER_INFO](state,username){
    for(let i = 0,len = users.length; iif(users[i].username === username){
        state = users[i];
        console.log(state);
      }
    }
  }
};

const getters = {
  userInfo : state => state
};
export default {
  state,
  getters,
  mutations
}

vue相关代码(signIn.vue)

computed:{
    ...mapGetters({
      user:'userInfo'
    })
  }

原因

state是个顶层容器,因此不能直接改变state,而是改变state.user
否则的话即使提交mutationstate的值也不会发生变化。

解决方法

let users = [
  {"username":"Lucy","password":"123456","login":false},
  {"username":"qweasd","password":"123456","login":false},
  {"username":"iopjkl","password":"123456","login":false}
];

const state =  {user:{...users[0]}};

const mutations = {
  [types.GET_USER_INFO](state,username){
    for(let i = 0,len = users.length; i<len; i++){
      if(users[i].username === username){
        state.user = users[i];
        console.log(state.user);
      }
    }
  }
};

const getters = {
  userInfo : state => state.user
};

你可能感兴趣的:(vue)