概述
在 Vue3.0 全面开放的大背景下,Vue 的周边生态迅速跟进,其中与 Vue 具有“血缘关系”的两个组件Vuex 和 Vue-Router 也相对应 Vue3.0 推出了全新的版本。
此次版本更新中,Vuex 大部分API都与之前的版本(Vuex3.0)相似,只有小部分发生了变动,Vue-Router相对来说发生了较大的变化
Vuex
Vuex 的变更首先体现在挂载方式和创建过程上,不再使用 Vuex.store 来实例化 store,直接使用 createStore 来创建 store
对比一下当前版本与上一版的区别
// vuex3
// /store/index.js
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 1
}
})
export default store
// main.js
import store from './store'
new Vue({store, render: h => h(App)}).$mount('#app')
// vuex4
// /store/index.ts
import { createStore, Store, useStore as baseUseStore } from 'vuex';
import { InjectionKey } from 'vue';
// import { moduleA } from "@/store/moduleA";
export interface State {
count: number;
// modules: {
// a: ReturnType<typeof moduleA>;
// };
}
export const key: InjectionKey<Store<State>> = Symbol();
export const store = createStore<State>({
state: {
count: 1,
},
mutations: {
COUNT_ADD(state) {
state.count++;
},
},
getters: {
count(state) {
return state.count;
},
},
// modules: {
// a: moduleA
// }
});
// 自定义 useStore
// 通过引入自定义的组合式函数,不用提供 injection key 和类型声明就可以直接得到类型化的 store
export function useStore() {
return baseUseStore(key);
}
// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { key, store } from './store';
const app = createApp(App);
app.use(router)
.use(store, key)
.mount('#app');
注意:在 main.ts 挂载 store 的时候必须传入 key,获取 store 的时候使用 key 来获取,本质上,Vuex 将store 安装到 Vue 应用中使用了 Vue 的 P