1、操作 cookie 工具 - src/utils/cookie.js
import Cookies from 'js-cookie'
export const Key = {
token: 'token',
userInfo: 'userInfo'
}
class CookieClass {
constructor() {
this.domain = process.env.VUE_APP_COOKIE_DOMAIN
this.expireTime = 15
}
set(key, value, expires, path = '/') {
CookieClass.checkKey(key)
Cookies.set(key, value, { expires: expires || this.expireTime, path: path, domain: this.domain })
}
get(key) {
CookieClass.checkKey(key)
return Cookies.get(key)
}
remove(key, path = '/') {
CookieClass.checkKey(key)
Cookies.remove(key, { path: path, domain: this.domain })
}
getAll() {
Cookies.get()
}
static checkKey(key) {
if (!key) {
throw new Error('没有找到key。')
}
if (typeof key === 'object') {
throw new Error('key不能是一个对象。')
}
}
}
export const PcCookie = new CookieClass()
2、获取 cookie 中的 token - userInfo - src/permission.js
import { PcCookie, Key } from '@/utils/cookie'
router.beforeEach(async(to, from, next) => {
const hasToken = PcCookie.get(Key.token)
if (hasToken) {
if (to.path === '/login') {
} else {
const hasGetUserInfo = PcCookie.get(Key.userInfo)
3、获取 cookie 中的属性 - 头像 - avatar
<script>
import { PcCookie, Key } from '@/utils/cookie'
export default {
components: {
Breadcrumb,
Hamburger
},
computed: {
avatar() {
return PcCookie.get(Key.userInfo) ? JSON.parse(PcCookie.get(Key.userInfo)).avatar : ''
}
},
4、删除 cookie
PcCookie.remove(Key.userInfo)
PcCookie.remove(Key.token)