简体   繁体   中英

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

When I want to update $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?

Nuxt provides $auth.setUser() method to set user.

Use $auth.setUser() like so:

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.

When you're using Vuex you should only mutate your state throught your mutations, in your Vuex you should create a mutation like this :

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

and in your component you need to map your new mutation in your methods ,

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

don't forget to import the mapMutations from vuex

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

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