简体   繁体   中英

Vuex mutator method unable to change state properties

I have the following code in a vuex module named user.js:

import Vue from "vue";
import Vuex from 'vuex';
Vue.use(Vuex);

const state = {
        user: {
            firstName: null,
            lastName: null,
            lastLogin: null,
            email: null,
            password: null,
            token: null
        }
    },
    actions = {
        setUser({commit}, user){
            commit('setUser', user);
        }
    },
    mutations = {
        setUser:(state, newuser) => {
            console.log(newuser) // Point 1
            console.log(state.user) // Point 2
            state.user.firstName = newuser.firstName;
            state.user.lastName = newuser.lastName;
            state.user.lastLogin = newuser.lastLogin;
            state.user.email = newuser.email;
            state.user.password = newuser.password;
            state.user.token = newuser.token;
            console.log(state.user) // Point 3
        }
    },
    getters = {
        getUser: (state) => state.user
    };
export default {
    state,
    actions,
    mutations,
    getters
}

The console shows that the passed object at Point 1 has populated properties, but the state.user.foo lines between Point 2 and Point 3 do not properly assign those values to the state object declared above.

A console log from Point 3 shows the following:

{…}
email: (...)
firstName: (...)
lastLogin: (...)
lastName: (...)
password: (...)
token: (...)

How can I get this mutator to actually change the state?

Changing the direct assignments to Vue.set(state, 'user', user) causes the state to properly update.

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