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; // 地址欄參數(shù)
userInfo: IUserInfo; // 登錄用戶信息
isLogin: boolean | string; // 用戶是否登錄
}
// 參數(shù)一:module名稱,開啟命名空間后會以name為命名空間
// 參數(shù)二:是否使用動態(tài)加載,簡而言之只有在用到當(dāng)前的module才會加載,詳細(xì)可以看vuex官網(wǎng)。
// 參數(shù)三:是否開啟命名空間,如果你的模塊很多,強(qiáng)烈建議開啟
//參數(shù)四:掛載的store目標(biāo)
@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中使用,可以用模塊直接調(diào)用,
在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>