Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
We all know that state management Vex4.x has some changes compared with vex3.x. In the following study, we will learn the usage of Vex4.x and understand where it has changed.
Store options
First, we create a store instance, which is different from vex3. x, as follows:
import { createStore } from 'vuex'
conststore = createStore({ ... options })Copy the code
Options in the above code is what we are going to talk about.
state
When we need data that is shared by many components or involves many levels of nesting, we can define the data in state. This is because Vuex’s state store is reactive, reading the state from a Store instance as follows:
Define the data
createStore({
state: {name:"Laughing"}})Copy the code
To get the data
In project development, we usually use auxiliary functions mapState and this.$store.state.name to get data.
mutations
Note that the only way to change the state in Vuex’s store is to commit mutation, which means that when we want to change the value of name, we have to commit mutation, as follows:
createStore({
state: {name:"Laughing"},mutations: {
changeName (state, name) {
state.name = name
}
}
})
Copy the code
The main thing we need is that the mutation method can pass two parameters: state and the data you need, and the second parameter is not written. If I wanted to change name to slifree, I could do this:
store.commit('changeName'.'slifree')
Copy the code
conclusion
The only way to change the state in Vuex’s store is to commit mutation. When we want to modify the state data, we can commit it.
For more articles, the portal has opened: Look back at the Vue3 catalogue!