Vuex4 極速入門到上手
vuex4 是 vue3的兼容版本,提供了和vuex3 的相同API。因此我們可以在 vue3 中復(fù)用之前已存在的 vuex 代碼。
一、安裝以及初始化
vuex4安裝:
- npm install vuex@next
為了向vue3初始化方式看齊,vuex4 初始化方式做了相應(yīng)的變化,使用新的 createStore 函數(shù)創(chuàng)建新的 store 實(shí)例。
- 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')
- //在組件內(nèi)使用時(shí)與之前一樣
- <div>{{$store.state.num}}</div>
二、vuex4在組件內(nèi)的使用
2.1、使用場(chǎng)景1
在組件的模板中直接使用,與之前的api保持一致
- // 在 main.js 內(nèi)
- const store = createStore({
- state(){
- return{
- num:1,
- }
- },
- mutations:{
- addNum(state){
- state.num++
- }
- },
- actions:{},
- modules:{}
- })
- //組件內(nèi)
- <div>
- {{$store.state.num}}
- <button @click="$store.commit('addNum')">num自加</button>
- </div>
2.2、使用場(chǎng)景2
通過(guò) useStore 把store 引入組件內(nèi),然后操作 store 。
- <template>
- <div>
- store組件
- {{state.num}}
- <button @click="add">num自加</button>
- </div>
- </template>
- <script>
- import { useStore } from "vuex"
- export default {
- setup(){
- const store = useStore()
- return{
- state:store.state,
- add(){
- store.commit('addNum')
- }
- }
- }
- }
- </script>
2.3、使用場(chǎng)景3
store 內(nèi)使用到多個(gè)值時(shí),可以通過(guò) toRefs 方法,將 store.state 內(nèi)的數(shù)據(jù)直接展開。
- <template>
- <div>
- {{num}}
- <button @click="add">num自加</button>
- </div>
- </template>
- <script>
- import { useStore } from 'vuex'
- import { toRefs } from "vue"
- export default {
- setup(){
- const store = useStore()
- return{
- ...toRefs(store.state),
- add(){
- store.commit('addNum')
- }
- }
- }
- }
- </script>
三、 getters 的用法
與之前的用法保持一致:
- const store = createStore({
- state(){
- return{
- num:1,
- }
- },
- getters:{
- doubleNum(state){
- return state.num*2
- }
- },
- })
- //使用1:直接在template中使用
- <template>
- {{$store.getters.doubleNum}}
- </template>
- //使用2:利用計(jì)算屬性獲取
- <template>
- <div>
- {{getDouble}}
- </div>
- </template>
- <script>
- import { useStore } from "vuex"
- import { computed } from 'vue'
- export default {
- setup(){
- const store = useStore()
- return{
- state:store.state,
- getDouble:computed(()=>store.getters.doubleNum)
- }
- }
- }
- </script>
四、mutations 和 actions 的用法
調(diào)用 mutations 內(nèi)的方法時(shí),使用 commit 調(diào)用。上述的使用場(chǎng)景2 就是 mutations 方法的調(diào)用。
而 actions 異步更新 state 中的數(shù)據(jù),還是需要經(jīng)過(guò) mutations 。
- <template>
- <div>
- {{state.num}}
- <button @click="asyncUpdateNum">更新num</button>
- </div>
- </template>
- <script>
- import { useStore } from "vuex"
- export default {
- setup(){
- const store = useStore()
- return{
- state:store.state,
- asyncUpdateNum(){
- store.dispatch('updateNum',88)
- }
- }
- }
- }
- </script>
組件內(nèi)可以通過(guò) this.$store 屬性訪問(wèn)store容器,使用 composition API 可以通過(guò) useStore代替。其他的用法基本相同。