cookie:有时也用其复数形式 Cookies。类型为“小型文本文件”,是某些网站为了辨别用户身份,进行Session跟踪而储存在用户本地终端上的数据(通常经过加密),由用户客户端计算机暂时或永久保存的信息
下载js-cookie模块
在utils文件夹中新建cookie.js文件,然后进行引入
import Cookies from 'js-cookie'
const TokenKey = 'ADMIN_DESIGN_KEY'
export function getToken() {
return Cookies.get(TokenKey)
}
export function setToken(token) {
return Cookies.set(TokenKey, token, {
expires: new Date(new Date().getTime() + 60 * 1000 * 60 ) //设置cookie有效期为1h,对应后端有效期
})
}
export function removeToken() {
return Cookies.remove(TokenKey)
}
用户登录以后,就可以根据后端返回的token来保存到本地cookie中,登录事件的处理函数如下
handleLogin() {
this.$refs.loginForm.validate(valid => {
const data = {
username: this.loginForm.username,
password: this.loginForm.password
}
if (valid) {
this.loading = true
login(data).then(res => {
this.loading = false
this.$store.dispatch('SET_PERMISSION', res.perms)
// 菜单权限
this.$store.commit('clearMenu')
this.$store.commit('setMenu', res.menuList)
sessionStorage.setItem('userInfo',JSON.stringify(res.userInfo))
this.$store.commit('addMenu', this.$router)
setToken(res.token)
this.$router.push({
path: '/'
})
}).catch(() => {
this.loading = false
})
}
})
}