Three ways to mutate pinia's state value

tanjiagang - Nov 2 - - Dev Community
  • the first method, directly assigning value(not recommended): useStore().stateItem = newVal.

  • the second, using $patch method. The parameter types of $path method has two ways:useStore().$patch(stateObject), which requires passsing an entire state object; The second type: useStore().$patch((state) =>{state.item = newVal}).

  • the third, calls to pinia's actions:

const useStore = defineStore('users', {
  state: ()=> ({
    count: 0
  }),

  actions: {
    increment: (newVal) => {
       this.count = newVal
    }
  }
})
Enter fullscreen mode Exit fullscreen mode
. . . . .