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...