Working with Pinia actions
Actions are the Pinia equivalent of component methods. They let you define custom logic for a store and can be asynchronous as well. This is useful for times when server-side logic needs to be called to validate a change to the state. Actions are defined with the actions
block of a Pinia object, and you can see an example in the default store created by Pinia:
import { defineStore } from 'pinia' export const useCounterStore = defineStore({ id: 'counter', state: () => ({ counter: 0 }), // rest of store... actions: { increment() { this.counter++ } } })
In this example, the increment
action simply takes the counter
value and adds one to it. Actions access state values by using the this
scope and, as stated previously, can be asynchronous as well. An example...