Vue3+TS在CompositionAPI下使用Vuex4

雖然在Vue3中可以使用Provide/Inject來(lái)實(shí)現(xiàn)超遠(yuǎn)距離變量傳送,但是只是祖父組件給子組件傳送。
如果要全局的進(jìn)行變量、狀態(tài)管理,還是要使用到Vuex。
針對(duì)Vue3的話(huà)版本就要升級(jí)到Vuex4。

先進(jìn)行包的安裝。注意針對(duì)Vue3的版本,vuex-composition-helpers需要安裝next版本。

$ npm install vuex@next -S
$ npm install vuex-composition-helpers@next -S

目錄結(jié)構(gòu)

└── store
    └── index.ts
└── main.ts

代碼

在代碼實(shí)現(xiàn)方式上,也有很大的不一樣,如下所示:

index.ts

import { InjectionKey } from 'vue';
import { ActionTree, createStore, GetterTree, MutationTree, Store, StoreOptions } from 'vuex';

// Declare state struct
declare interface globalStore {
  fakeName: string;
}

// Define All params of StoreOptions
const globalStoreState: globalStore = {
  fakeName: 'Fake Name',
};

const globalStoreGetters: GetterTree<globalStore, any> = {
  fakeName: (state) => state.fakeName,
};

const globalStoreMutations: MutationTree<globalStore> = {
  UPDATE_FAKE_NAME(state, payload) {
    state.fakeName = payload;
  },
};

const globalStoreActions: ActionTree<globalStore, any> = {
  updateFakeName({ commit }, payload) {
    commit('UPDATE_FAKE_NAME', payload);
  },
};

// Define StoreOptions
const globalStoreOption: StoreOptions<globalStore> = {
  state: globalStoreState,
  getters: globalStoreGetters,
  mutations: globalStoreMutations,
  actions: globalStoreActions,
};

// Defind current store key
export const globalStoreKey: InjectionKey<Store<globalStore>> = Symbol();

export default createStore<globalStore>(globalStoreOption);

main.ts

import { createApp } from 'vue';
import App from './App.vue';

import store, { globalStoreKey } from './store';

const app = createApp(App);
// use store
app.use(store, globalStoreKey);

app.mount('#app');

component.vue

<template>
   <p>{{ fakeName }}</p>
</template>
<script lang="ts">
import { defineComponent, inject, reactive, ref } from 'vue';
import { useStore } from 'vuex';
import { globalStoreKey } from '../store';
import { useState, useActions } from 'vuex-composition-helpers';

export default defineComponent({
    setup() {
       // 通過(guò)key拿到特定的store
       const store = useStore(globalStoreKey);
       // 這里的 useActions 類(lèi)似之前vuex的mapActions
       const { updateFakeName } = useActions(store, ['updateFakeName']);

       return  {
           // 這里的 useState 類(lèi)似之前vuex的 mapGetters
           ...useState(store, ['fakeName']),
       }
    }
})
</script>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容