Vuex结构目录
目录结构
├─ src/ │ ├─ store/ │ ├─── modules/ │ │ ├─ user.ts │ ├─── index.ts
index.ts 代码
import Vue from "vue"; import Vuex from "vuex"; import { IUserState } from "./modules/user"; Vue.use(Vuex); export interface IRootState { user: IUserState; } // Declare empty store first, dynamically register all modules later. export default new Vuex.Store<IRootState>({});
vuex-module-decorators
vuex-module-decorators,它是基于vue-class-component所做的拓展,它提供了一系列的装饰器,让vue+ts结合的项目达到状态管理的作用。
import { Module, VuexModule, Action, Mutation, getModule } from "vuex-module-decorators";
[@Module](/user/Module)
`/**
- dynamic: true: 动态创建动态模块,即new Vuex.Store({})里面不用注册的
- store,当前模块注册到store上
- name: ‘user’ 命名空间为user */ @Module({ dynamic: true, store, name: ‘user’ })`
VuexModule
export interface IUserState { token: string; name: string; email: string; }
在里面定义的属性相当于state
class User extends VuexModule implements IUserState{ public token = getToken() || ""; public name = ""; public email = ""; }
[@Mutation](/user/Mutation) 相当于 mutation,作为唯一修改数据的途径
[@Mutation](/user/Mutation) private SET_TOKEN(token: string) { this.token = token; } [@Mutation](/user/Mutation) private SET_NAME(name: string) { this.name = name; } [@Mutation](/user/Mutation) private SET_EMAIL(email: string) { this.email = email; }
[@Action](/user/Action) 相当于 axtion, action发出修改数据的指令,在mutation中修改数据
[@Action](/user/Action) public async Login(userInfo: { username: string; password: string }){ let { username, password } = userInfo; username = username.trim(); // 这里发出登陆请求 const { data } = await login({ username, password }); setToken(data.accessToken); this.SET_TOKEN(data.accessToken); if (username === "admin" && password === "admin") { setToken("admin"); this.SET_TOKEN("admin"); } }
getModule 将模块导出
export const UserModule = getModule(User);
Vuex的使用
这里简单记录一下vuex的原理, 在index.ts中我们使用
Vue.use(Vuex)
,在vuex内部会有个init用来初始化,然后通过mixin
的当时将vuexInit
方法混淆进beforeCreate
钩子中,并用 Vue 保存 Vue 对象。
import store from "./store"; new Vue({ router, store, render: h => h(App) }).$mount("#app");
// 引入UserModule模块 import { UserModule } from "@/store/modules/user"; async onSubmit(values: { username: string; password: string }) { await UserModule.Login(values); }
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 作者: 疯狂打代码 原文链接:https://juejin.im/post/6844904194969698317