一、Vuex4介绍
vuex 是一个专为 Vue.js 应用程序开发的状态管理模式+库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。vuex包括五大核心概念分别是State、Getter、Mutation、Action、Module。参考官网:vuex官网
二、 Vuex安装
//现在默认是vuex3,所以加上next安装下一个版本
npm install vuex@next
//package.json文件中,查看版本
"dependencies": {
"vuex": "^4.0.2"
},
三、Vuex使用
1、创建store对象
vuex4引入了createStore方法,来创建一个store对象。createStore方法接收一个泛型,对state类型进行限定。引入module将store分割,每个module拥有自己的 state、mutation、action、getter,避免store对象臃肿。如下创建一个store对象,并将其分割成app和user两个module。
import { createStore } from 'vuex';
// 对state的类型进行限定
export interface IRootState {
user: IUserState;
app: IAppState;
}
// 创建store对象
export const store = createStore<IRootState>({
modules: {
app,
user,
},
});
2、定义模块
首先vuex4对模块类型定义如下,S是模块中state的类型限定,R是根store中的state的类型限定
export interface Module<S, R> {
namespaced?: boolean;
state?: S | (() => S);
getters?: GetterTree<S, R>;
actions?: ActionTree<S, R>;
mutations?: MutationTree<S>;
modules?: ModuleTree<R>;
}
定义app模块如下
import { Module, ActionTree, GetterTree, MutationTree } from 'vuex';
const data = {};
const mutations: MutationTree<IAppState> = {};
const actions: ActionTree<IAppState, IRootState> = {};
const getters: GetterTree<IAppState, IRootState> = {};
const appModule: Module<IAppState, IRootState> = {
state: data,
actions,
mutations,
getters,
};
export default appModule;
vuex 4 引入了一个新的 API 用于在组合式 API 中与 store 进行交互。可以在组件的 setup
钩子函数中使用 useStore
组合式函数来检索 store。
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
}
}
3、注册到main.ts中,这样各个组件中就可以使用store对象了。
// main.ts文件中
import { createApp } from 'vue'
import store from '@/store'
const app = createApp(App)
app.use(store)
app.mount('#app')
四、总结
vuex4
的改动相对来说不是很大,除了创建和获取有些区别,使用和以前还是一模一样的。需要注意的是辅助函数那一块,它是不能在组合式写法setup
中使用的。也可参考相关文章:vuex4的基本使用(typescript)