modules 添加user.js
import { setStore, getStore, removeStore } from '@/utils/tools'
import {
getInfo, login as loginApi, logout as logoutApi
} from '@/api'
// import { login, logout, getInfo } from '@/api'
const user = {
namespaced: false,
state: {
userId: getStore('userId'), // 当前用户id
account: getStore('account'), // 用户账号
name: '', // 用户真实姓名
perms: [], // 权限路径
roles: [], // 权限路径
phonenumber: '', // 当前用户手机号
token: getStore('token') // 系统token
},
mutations: {
SET_TOKEN (state, val) {
state.token = val
if (val) {
setStore('token', val)
} else {
removeStore('token')
}
},
SET_USER_ID (state, val) {
// console.log('SET_USER_ID', val, val || val === 0)
state.userId = val
if (val || val === 0) {
setStore('userId', val)
} else {
removeStore('userId')
}
},
SET_PERMS (state, val) {
state.perms = val || []
},
SET_ROLES (state, val) {
state.roles = val || []
},
SET_ACCOUNT (state, val) {
state.account = val
if (val) {
setStore('account', val)
} else {
removeStore('account')
}
},
SET_NAME (state, val) {
state.name = val
},
SET_PHONE (state, val) {
state.phonenumber = val
}
},
actions: {
// 登录
login ({ commit, state }, val) {
return new Promise((resolve, reject) => {
loginApi(val).then(res => {
console.log('res', res, res.code === 200)
if (res.code === 200) {
commit('SET_TOKEN', res?.data?.token)
setUserInfo(commit, res?.data)
return resolve()
} else {
return reject(res)
}
}).catch(err => {
console.log(err)
return reject(err)
})
})
},
logOut ({ commit }) {
return new Promise((resolve, reject) => {
logoutApi().then(res => {
if (res.code === 200) {
commit('SET_TOKEN', '')
setUserInfo(commit)
// commit('SET_SYSTEM_LABEL', '')
return resolve(res)
} else {
return reject(res)
}
}).catch(err => {
return reject(err)
})
})
},
// 重加载用户信息
reloadUserInfo ({ commit, state, getters }) {
return new Promise((resolve, reject) => {
getInfo().then(res => {
if (res?.code === 200) {
setUserInfo(commit, res.data.user)
return resolve(getters.getPerms)
} else {
return reject(res)
}
}).catch(err => {
return reject(err)
})
})
},
// 清空用户信息
clearUserInfo ({ commit }) {
commit('SET_TOKEN', '')
commit('SET_SYSTEM_LABEL', '')
setUserInfo(commit)
}
}
}
function setUserInfo (commit, data = {}) {
// console.log('data', data?.id)
commit('SET_USER_ID', data?.id || '')
commit('SET_ACCOUNT', data?.account || '')
commit('SET_NAME', data?.name || '')
commit('SET_PHONE', data?.phonenumber || '')
commit('SET_PERMS', data?.perms ? data?.perms.map(p => p?.pval) : [])
commit('SET_ROLES', data?.roles ? data?.roles.map(r => r?.grade) : [])
}
export default user
getters.js
const getters = {
token: state => state.user.token,
getUserId: state => state.user.userId,
getPerms: state => state.user.perms
}
export default getters
index.js
···
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import getters from './getters'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
user
},
getters
})
export default store
···
网友评论