In this tutorial, we will learn how to work with actions and asynchronous (async) data in Vuex. Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application.
Actions in Vuex are similar to mutations, but there are two main differences:
- Actions commit mutations.
- Actions can contain arbitrary asynchronous operations.
Let's look at an example of an action:
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
In this example, we use the setTimeout
JavaScript function to simulate an async operation. After one second, our action commits the increment
mutation.
// Defining the Vuex store
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment ({ commit }) {
commit('increment')
}
}
})
// Dispatching the action
store.dispatch('increment')
In this example, we define a Vuex store with a simple state: count
. We then define a mutation increment
which increases the count
by 1, and an action increment
which commits the increment
mutation. Finally, we dispatch the increment
action, which results in the count
being increased by 1.
// Defining the Vuex store
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
})
// Dispatching the async action
store.dispatch('incrementAsync')
In this example, we define an async action incrementAsync
. This action waits for 1 second before committing the increment
mutation.
In this tutorial, we've learned how to handle actions and async operations in Vuex. We've learned how to commit mutations and dispatch actions.
For further learning, you can look into Vuex modules, which allow for more complex state management. You can also explore how to use Vuex with Vue Router for route-level state management.
Exercise 1: Create a Vuex store with a state that contains a list of todos. Each todo should have a title
and a completed
property. Define a mutation addTodo
that adds a new todo to the list, and an action addTodoAsync
that commits the addTodo
mutation after a delay of 1 second.
Exercise 2: Extend the Vuex store from exercise 1 by adding a mutation toggleTodo
that toggles the completed
property of a todo, and an action toggleTodoAsync
that commits the toggleTodo
mutation after a delay of 1 second.
Exercise 3: Further extend the Vuex store from exercise 2 by adding a getter completedTodos
that returns all todos where completed
is true
.