import { login } from 'api/user'
import { Toast } from 'vant'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
// import router from '@/router'
const LOGIN = 'LOGIN'// 获取用户信息
const SetUserData = 'SetUserData'// 获取用户信息
const LOGOUT = 'LOGOUT'// 退出登录、清除用户数据
const USER_DATA = 'userData'// 用户数据
const SetLectureType = 'SetLectureType' // 课程类型
export default {
namespaced: true,
state: {
token: getToken() || '',
user: JSON.parse(localStorage.getItem(USER_DATA) || null),
lectureType: 1
},
mutations: {
[LOGIN] (state, data) {
let userToken = data.data
state.token = userToken
setToken(userToken)
},
[SetUserData] (state, userData = {}) {
state.user = userData
localStorage.setItem(USER_DATA, JSON.stringify(userData))
},
[SetLectureType] (state, lectureType) {
state.lectureType = lectureType
},
[LOGOUT] (state) {
state.user = null
state.token = null
removeToken()
localStorage.removeItem(USER_DATA)
resetRouter()
}
},
actions: {
async login (state, data) {
try {
let res = await login({
phoneNumber: data.phoneNumber,
password: data.password
})
state.commit(LOGIN, res)
Toast({
message: '登录成功',
position: 'middle',
duration: 1500
})
setTimeout(() => {
const redirect = data.$route.query.redirect || '/'
data.$router.replace({
path: redirect
})
}, 1500)
} catch (error) {
}
},
SetLectureType ({ commit }, lectureType) { // 写入课程类型的筛选id
commit(SetLectureType, lectureType)
},
// get user info
getInfo ({ commit, state }) {
return new Promise((resolve, reject) => {
commit(SetUserData, { 'userId': '3301' })
})
}
},
getters: {
token (state) {
return state.token
},
user (state) {
return state.user
},
lectureType (state) {
return state.lectureType
}
}
}
localstorage store结合存数据
最新推荐文章于 2022-10-22 17:21:13 发布