首页 > 解决方案 > 更新 Vuex 存储中的数据而不是替换它

问题描述

我的 Nuxt store/index.js 文件中有以下数据:

export const state = () => ({
    user: {
        status: 'signedin',
        data: {
            'salutation': 'Mr',
            'firstname': 'Test',
            'lastname': 'Person',
            'emailaddress': 'test@test.com'
        }
    }
});

我想更新“数据”部分中的某些值,但不更新其他值……例如,我想将“名字”更改为“大卫”,但其余数据保持不变。请有人能指出我正确的方向吗?

标签: vue.jsvuejs2vuexnuxt.js

解决方案


你应该可以用一个mutation做到这一点。可以在此处找到更新子属性的示例:CodePen

在您的情况下,您的突变看起来像这样:

{
...
  mutations: {
    UPDATE_FIRST_NAME(state, value) {
      state.user.data.firstname = value;
    }
  }
...
}
// Call the mutation
this.$store.commit('UPDATE_FIRST_NAME', 'David')


推荐阅读