Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
The use of state management in Vue3 is somewhat different from Vue2. We need to obtain the store instance first and then use the corresponding method.
Use of state management in Vue3
We can access the Store in the Setup hook function by calling the useStore function. This is equivalent to accessing this.$store using the optional API in the component as follows:
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
}
}
Copy the code
It is important to note that you must use useStore in setup before you can use the store instance method.
Use State and Getter
To access state and getter, you need to create computed references to preserve responsiveness, which is equivalent to creating computed properties in the optional API, as follows:
import { computed } from 'vue'
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
return {
// Access state in a computed function
count: computed(() = > store.state.count),
// Access the getter in a computed function
double: computed(() = > store.getters.double)
}
}
}
Copy the code
One thing we need to be careful about is using computed methods to keep our data responsive.
Use Mutation and Action
To use mutation and action, you simply call the COMMIT and dispatch functions in the Setup hook function.
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
return {
/ / using mutation
increment: () = > store.commit('increment'),
/ / use the action
asyncIncrement: () = > store.dispatch('asyncIncrement')}}}Copy the code
conclusion
The first step is to get the store instance through the useStore method and then use the state or call the corresponding function, but remember that useStore is only used in the setup function.
For more articles, the portal has opened: Look back at the Vue3 catalogue!