Actions help you change data in your app in a clear and organized way. They let you update state safely and keep your app working smoothly.
0
0
Actions for modifying state in Vue
Introduction
When you want to update data based on user clicks or input.
When you need to change state after fetching data from a server.
When you want to keep your state changes easy to track and test.
When multiple parts of your app need to update the same data.
When you want to separate how you change data from where you use it.
Syntax
Vue
const store = createStore({ state() { return { count: 0 } }, mutations: { increment(state) { state.count++ }, incrementBy(state, payload) { state.count += payload } }, actions: { increment(context) { context.commit('increment') }, incrementBy(context, payload) { context.commit('incrementBy', payload) } } })
Actions are functions inside the actions object in your store.
They receive a context object to access state and other helpers.
Examples
This action adds 1 to the count.
Vue
actions: {
increment(context) {
context.commit('increment')
}
}This action adds a given number to the count.
Vue
actions: {
incrementBy(context, amount) {
context.commit('incrementBy', amount)
}
}Sample Program
This Vue app uses a store with actions to change the count. Clicking buttons calls actions to update the state, and the count updates on screen.
Vue
import { createApp } from 'vue' import { createStore } from 'vuex' const store = createStore({ state() { return { count: 0 } }, mutations: { increment(state) { state.count++ }, incrementBy(state, amount) { state.count += amount } }, actions: { increment(context) { context.commit('increment') }, incrementBy(context, amount) { context.commit('incrementBy', amount) } } }) const app = createApp({ computed: { count() { return store.state.count } }, methods: { addOne() { store.dispatch('increment') }, addFive() { store.dispatch('incrementBy', 5) } }, template: ` <div> <p>Count: {{ count }}</p> <button @click="addOne">Add 1</button> <button @click="addFive">Add 5</button> </div> ` }) app.use(store) app.mount('#app')
OutputSuccess
Important Notes
Actions can be asynchronous if you need to wait for data before changing state.
Use store.dispatch('actionName', payload) to call actions.
Do not change state directly outside mutations to keep your app predictable.
Summary
Actions are special functions to change app data safely.
They help keep your code organized and easy to understand.
Use dispatch to run actions and update state.