Vuex structure directory
The directory structure
├ ─ SRC /│ ├ ─ store /│ ├ ─ ─ ─ modules /│ │ ├ ─ user. Ts│ ├ ─ ─ ─ index. TsCopy the code
Index. Ts code
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>({}); Copy the code
vuex-module-decorators
Vuex-module-decorators, an extension of vuUe-class-Component, provide a set of decorators that enable state management for vUE + TS combined projects.
import {
Module,
VuexModule,
Action,
Mutation,
getModule } from "vuex-module-decorators"; Copy the code
@Module
/ * ** dynamic: trueNew vuex.store ({}) creates dynamic modules dynamically* Store, the current module is registered with store* name: 'user'The namespace is user* /@Module({ dynamic: true, store, name: 'user' }) Copy the code
VuexModule
export interface IUserState {
token: string;
name: string;
email: string;
}
Copy the code
Properties defined inside are equivalent to state
class User extends VuexModule implements IUserState{
public token = getToken() || "";
public name = "";
public email = "";
}
Copy the code
@mutation is equivalent to Mutation as the only way to modify data
@Mutation
private SET_TOKEN(token: string) {
this.token = token;
}
@Mutation private SET_NAME(name: string) { this.name = name; } @Mutation private SET_EMAIL(email: string) { this.email = email; } Copy the code
The @action is equivalent to the axtion, which issues the instruction to modify the data and changes the data in mutation
@Action
public async Login(userInfo: { username: string; password: string }){
let { username, password } = userInfo;
username = username.trim();
// Here is a login request 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"); } } Copy the code
GetModule exports the module
export const UserModule = getModule(User);
Copy the code
The use of Vuex
VuexInit (vuex) is used for vuex initialization. For each vuex hook, the vuexInit method is used for each vuex hook. For each vuex hook, the vuexInit method is used for each vuex hook. Save Vue objects with Vue.
import store from "./store";
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app"); Copy the code
// Import the UserModule moduleimport { UserModule } from "@/store/modules/user";
async onSubmit(values: { username: string; password: string }) {
await UserModule.Login(values);
} Copy the code