简体   繁体   English

如何更新 Nuxt.js 中的 $auth.user 属性?

[英]How to update $auth.user properties in Nuxt.js?

When I want to update $auth.user.balance :当我想更新$auth.user.balance

methods:{
   test(){
      this.$auth.user.balance = 10;
   }
}

But it returns error:但它返回错误:

Error: [vuex] do not mutate vuex store state outside mutation handlers.

How can I update these vuex properties in Nuxtjs?如何在 Nuxtjs 中更新这些 vuex 属性?

Nuxt provides $auth.setUser() method to set user. Nuxt 提供了$auth.setUser()方法来设置用户。

Use $auth.setUser() like so:像这样使用$auth.setUser()

const updatedUser = {...this.$auth.user}
updatedUser.balance = 10;
this.$auth.setUser(updatedUser)

Data updating in store always should be immutable.存储中的数据更新始终应该是不可变的。

So create a new reference of object before passing it to setUser to avoid the reactivity issue.因此,在将对象传递给setUser之前创建一个新的对象引用以避免反应性问题。

When you're using Vuex you should only mutate your state throught your mutations, in your Vuex you should create a mutation like this :当你使用 Vuex 时,你应该只通过你的突变来改变你的状态,在你的 Vuex 中你应该创建一个这样的突变:

  setBalance(state, payload) {
    auth.user.balance = payload;
  },

and in your component you need to map your new mutation in your methods ,在你的组件中,你需要在你的methods映射你的新突变,

 ...mapMutations('auth', ['setBalance']),

don't forget to import the mapMutations from vuex不要忘记从 vuex 导入 mapMutations

import { mapMutations } from 'vuex';

and in your component when you want to set a new value to balance you call并在您的组件中,当您想设置一个新值来平衡时,您调用

 test(){
         let newValue = 10;
         this.setBalance(newValue);
       }

You can learn more about mutations in Vuex store here in Vuex documentation您可以了解更多关于突变Vuex店这里Vuex文档中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM