guoyu/fronted_uniapp/store/modules/auth.js

60 lines
1.3 KiB
JavaScript
Raw Normal View History

2025-12-03 18:58:36 +08:00
import auth from '@/utils/auth.js'
const state = {
token: uni.getStorageSync('token') || '',
userInfo: uni.getStorageSync('userInfo') || {}
}
const mutations = {
SET_TOKEN(state, token) {
state.token = token
uni.setStorageSync('token', token)
},
SET_USER_INFO(state, userInfo) {
state.userInfo = userInfo
uni.setStorageSync('userInfo', userInfo)
},
CLEAR_AUTH(state) {
state.token = ''
state.userInfo = {}
uni.removeStorageSync('token')
uni.removeStorageSync('userInfo')
}
}
const actions = {
async login({ commit }, { username, userType, code, uuid }) {
try {
// 仅用户名登录,不需要密码
const data = await auth.login(username, userType, code, uuid)
commit('SET_TOKEN', data.token)
commit('SET_USER_INFO', data.userInfo || {})
return data
} catch (error) {
throw error
}
},
async logout({ commit }) {
try {
await auth.logout()
} finally {
commit('CLEAR_AUTH')
}
}
}
const getters = {
isLoggedIn: state => !!state.token,
userInfo: state => state.userInfo,
userRole: state => state.userInfo.role || ''
}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}