Vue3+TS在CompositionAPI下使用Vuex4

虽然在Vue3中可以使用Provide/Inject来实现超远距离变量传送,但是只是祖父组件给子组件传送。
如果要全局的进行变量、状态管理,还是要使用到Vuex。
针对Vue3的话版本就要升级到Vuex4。

先进行包的安装。注意针对Vue3的版本,vuex-composition-helpers需要安装next版本。

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

目录结构

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

代码

在代码实现方式上,也有很大的不一样,如下所示:

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 = {
  fakeName: (state) => state.fakeName,
};

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

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

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

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

export default createStore(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



你可能感兴趣的:(Vue3+TS在CompositionAPI下使用Vuex4)