操作 js-cookie 获取 cookie 中的 token userInfo 用户头像

1、操作 cookie 工具 - src/utils/cookie.js

import Cookies from 'js-cookie'

// Cookie的key值
export const Key = {
  token: 'token', // 访问令牌在 cookie 的 key值 ++
  userInfo: 'userInfo' // 用户信息 在cookie 中的key值 ++
}

class CookieClass {
  constructor() {
    // .env.production / .env.development 中配置
    this.domain = process.env.VUE_APP_COOKIE_DOMAIN // 域名
    this.expireTime = 15 // cookie 有效时长 单位 天
  }

  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' // 导入操作cookie工具 ++

router.beforeEach(async(to, from, next) => {

  // 从 cookie 中获取访问令牌
  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: {
    // 从 cookie 获取用户头像 ++ 💥
    avatar() {
      return PcCookie.get(Key.userInfo) ? JSON.parse(PcCookie.get(Key.userInfo)).avatar : ''
    }
  },

4、删除 cookie

 PcCookie.remove(Key.userInfo)
 PcCookie.remove(Key.token)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值