index.ts 2.38 KB
import { defineStore } from 'pinia'
import { setToken, getToken, removeToken } from '../utils/auth'

export const loginMain = defineStore('loginMain', {
    // 相当于data
    state: () => {
        return {
            // 所有这些属性都将自动推断其类型,如果推断失败可以试下 as xxx
            userInfo: null,
            token: null,
            userType: null,
            isWait: false,
            timeCount: 60,
            registerTimer: null,
            activeName: 'noFinish',
        }
    },
    // 相当于计算属性
    getters: {
        getUserInfo: (state)=> {
            return state.userInfo
        },
        getStoreToken: (state)=> {
            return state.token
        },
        getIsWait: (state)=> {
            return state.isWait
        },
        getTimeCount: (state)=> {
            return state.timeCount
        },
        getRegisterTimer: (state)=> {
            return state.registerTimer
        },
        getActiveName: (state)=> {
            return state.activeName
        },
    },
    // 相当于vuex的 mutation + action,可以同时写同步和异步的代码
    actions: {
        setUserInfo(userInfo: object) {
            this.token = getToken()
            window.sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
            // @ts-ignore
            this.userInfo = userInfo
            // this.userType = Object.keys(userInfo).length > 0 && userInfo.userType || ''
        },
        setWait(val:boolean) {
            this.isWait = val
        },
        setTimeCount(val: any) {
            this.timeCount = val
        },
        setRegisterTimer() {
            this.registerTimer = null
            this.timeCount = 60
        },
        refreshUserInfo() {
            this.token = getToken()
            if (window.sessionStorage.getItem('userInfo')) {
                this.userInfo = JSON.parse(<string>window.sessionStorage.getItem('userInfo'))
                // let userInfo = this.userInfo
                // this.userType = Object.keys(userInfo).length > 0 && userInfo.userType || ''
            }
        },
        removeUserInfo() {
            window.sessionStorage.removeItem('userInfo')
            this.userInfo = null
            this.userType = null
            this.token = null
            removeToken()
        },
        setActiveName(val: string) {
            this.activeName = val
        }
    },
})