vuex-module-decorators
import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators';
import store from '@/store';
import { IUserInfo, login, loginOut } from '@/api/user-info';
import { CODE_SERVER } from '@/utils/enums';
import { getUserInfoBySession, removeUserInfoBySession, setUserInfoBySession } from '@/utils/session';
export interface IUserState {
query: object; // 地址栏参数
userInfo: IUserInfo; // 登录用户信息
isLogin: boolean | string; // 用户是否登录
}
// 参数一:module名称,开启命名空间后会以name为命名空间
// 参数二:是否使用动态加载,简而言之只有在用到当前的module才会加载,详细可以看vuex官网。
// 参数三:是否开启命名空间,如果你的模块很多,强烈建议开启
//参数四:挂载的store目标
@Module({ name: 'user',dynamic: true,namespaced: true, store })
class User extends VuexModule implements IUserState {
public userInfo: IUserInfo = getUserInfoBySession();
public query: object = {};
@Mutation
public SET_IS_LOGIN(val: any) {
this.isLogin = val;
}
@Action
public setLogin(val: any) {
this.SET_IS_LOGIN(val);
}
@Mutation
private SET_QUERY(query: any) {
this.query = query;
}
@Action
public setQuery(query: any) {
this.SET_QUERY(query);
}
}
export const UserModule = getModule(User);
使用:
在js中使用,可以用模块直接调用,
在html中只能用$store.XXX
<template>
<div>
<el-input v-model="aaa" @blur="changeVal"></el-input>
<br>
{{$store.state.user.message}}
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import {UserModule} from '@/store/module/user'
@Component
export default class User extends Vue {
private aaa = '';
private changeVal(){
console.log(UserModule.message);
UserModule.getUser(this.aaa);
}
}
</script>