Preface
Using Vuex for state management in Vue 3 is a good practice, especially when it comes to sharing state among multiple components. Here is a tutorial on how to set up and use Vuex in a Vue 3 project, including the concepts of state, mutations, actions, getters and their purpose.
1. Install Vuex
First make sure your project has Vue CLI installed and is Vue 3 version. Then install Vuex:
npm install vuex@next --save
Or use Yarn:
yarn add vuex@next --save
2. Initialize the Vuex Store
In Vue 3, Vuex is implemented slightly differently, mainly by using the Composition API. Create a name calledfile and initialize Vuex:
import { createStore } from 'vuex'; const store = createStore({ state: { count: 0, }, mutations: { increment(state) { ++; }, }, actions: { increment(context) { ('increment'); }, }, getters: { doubleCount(state) { return * 2; }, }, }); export default store;
3. Configure the Vue app to use the Vuex Store
In your entry file (usuallyor
) Configure Vuex store:
import { createApp } from 'vue'; import App from './'; import store from './store'; const app = createApp(App); (store); ('#app');
4. Use Vuex in Vue components
Using State
Use the Composition API to access state in Vuex:
<template> <div>{{ count }}</div> </template> <script setup> import { useStore } from 'vuex'; const store = useStore(); const count = ; </script>
Using Mutations
Mutations is used to synchronize update status:
<template> <button @click="increment">Increment</button> </template> <script setup> import { useStore } from 'vuex'; const store = useStore(); function increment() { ('increment'); } </script>
Use Actions
Actions provide a place for asynchronous operations, which are usually used to handle asynchronous operations such as network requests:
<template> <button @click="incrementAsync">Increment Async</button> </template> <script setup> import { useStore } from 'vuex'; const store = useStore(); async function incrementAsync() { await ('increment', { amount: 5 }); } </script>
Use Getters
Getters provides the function of calculating derived data of state:
<template> <div>{{ doubleCount }}</div> </template> <script setup> import { useStore } from 'vuex'; const store = useStore(); const doubleCount = ; </script>
5. Summary
- State: Where data is stored, all components can access it.
- Mutations: The only way to update state, and must be a synchronous function.
- Actions: The method of submitting mutation can contain any asynchronous operations.
- Getters: Process the data in state and return new derivative data.
6. Vuex helper functions
In Vue 3, you can use Vuex's combined API to manage state, which includes helper functions such as useStore, mapState, mapGetters, mapActions, and mapMutations. However, in Vue 3, it is recommended to use the setup function and the Composition API (Composition API) to organize logic.
useStore
useStore
is a combined API function that returns a reference to the current store.
import { useStore } from 'vuex'; export default { setup() { const store = useStore(); return { store }; } }
mapState
mapState
Return object used to map state to a composite API.
import { mapState } from 'vuex'; export default { setup() { const { count } = mapState(['count'])(); return { count }; } }
mapGetters
mapGetters
Return object used to map getters to composite APIs.
import { mapGetters } from 'vuex'; export default { setup() { const { doubleCount } = mapGetters(['doubleCount'])(); return { doubleCount }; } }
mapMutations
mapMutations
Methods for mapping mutations to a composite API.
import { mapMutations } from 'vuex'; export default { setup() { const { increment } = mapMutations(['increment']); return { increment }; } }
mapActions
mapActions
Methods for mapping actions to a composite API.
import { mapActions } from 'vuex'; export default { setup() { const { fetchCount } = mapActions(['fetchCount']); return { fetchCount }; } }
Example of usage
Suppose you have a name calledcounter
module, and you want to use it in the component:
// store/modules/ const state = { count: 0, }; const getters = { doubleCount(state) { return * 2; }, }; const mutations = { increment(state) { ++; }, }; const actions = { async fetchCount({ commit }) { // Simulate asynchronous operations await new Promise(resolve => setTimeout(resolve, 1000)); commit('increment'); }, }; export default { namespaced: true, state, getters, mutations, actions, };
In your Vue 3 component, you can use it like this:
<template> <div> {{ count }} <button @click="increment">Increment</button> <button @click="fetchCount">Fetch Count</button> </div> </template> <script> import { useStore } from 'vuex'; import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'; export default { setup() { const store = useStore(); const { count } = mapState({ count: state => })(); const { doubleCount } = mapGetters({ doubleCount: 'counter/doubleCount' })(); const { increment } = mapMutations({ increment: 'counter/increment' }); const { fetchCount } = mapActions({ fetchCount: 'counter/fetchCount' }); return { count, doubleCount, increment, fetchCount, }; }, }; </script>
Things to note
- use
mapState
,mapGetters
,mapMutations
,mapActions
When you want to make sure they are called as functions, and the returned objects need to be deconstructed and assigned to the responsive variables in the component. - If your modules are namespaced, you need to reference them correctly.
- In Vue 3, Vuex's helper functions need to be coordinated
setup
Functions are used and are usually used with the Composition API.
These helper functions can help you more easily use Vuex to manage state in Vue 3, while also making the code more readable and maintainable.
The above is the detailed tutorial on using Vuex for state management in Vue3 project. For more information about Vue3 Vuex status management, please follow my other related articles!