vuex4 Get started quickly
vuex4 is a compatible version of vue3 and provides the same API as vuex3. So we can reuse the existing vuex code in vue3.
Recommended learning: "The latest 5 vue.js video tutorial selections"
1. Installation and initialization
vuex4 installation:
npm install vuex@next
In order to align with the vue3 initialization method, the vuex4 initialization method has been changed accordingly, using the new createStore function to create a new store instance.
import { createApp } from 'vue' import App from './App.vue' import router from './router' import { createStore } from "vuex" const store = createStore({ state(){ return{ num:1, } } }) const app = createApp(App) app.use(router) app.use(store) app.mount('#app') //在组件内使用时与之前一样{{$store.state.num}}
2. The use of vuex4 in the component
2.1. Usage scenario 1
Use it directly in the template of the component, which is the same as the previous api Keep it consistent
// 在 main.js 内 const store = createStore({ state(){ return{ num:1, } }, mutations:{ addNum(state){ state.num++ } }, actions:{}, modules:{} }) //组件内{{$store.state.num}}
2.2. Usage scenario 2
Introduce the store into the component through useStore, and then operate the store.
store组件 {{state.num}}
2.3. Usage Scenario 3
When multiple values are used in the store, the data in store.state can be directly expanded through the toRefs method.
{{num}}
3. The usage of getters
is consistent with the previous usage:
const store = createStore({ state(){ return{ num:1, } }, getters:{ doubleNum(state){ return state.num*2 } }, }) //使用1:直接在template中使用 {{$store.getters.doubleNum}} //使用2:利用计算属性获取{{getDouble}}
4. The usage of mutations and actions
When calling methods within mutations, use commit. The above usage scenario 2 is the call of mutations method.
And actions asynchronously update the data in state, they still need to go through mutations.
{{state.num}}
The store container can be accessed through the this.$store property in the component, and the composition API can be used instead through useStore. Other usages are basically the same.
The above is the detailed content of Take you step by step to quickly get started with vuex4!. For more information, please follow other related articles on the PHP Chinese website!