简单封装浏览器 cookie 工具类

版权声明:本文首发 http://asing1elife.com ,转载请注明出处。 https://blog.csdn.net/asing1elife/article/details/82655713

简单封装浏览器 cookie 工具类

目前主流浏览器一般都支持 cookie ,以下对 cookie 的操作进行简单封装,以方便使用

更多精彩

主体封装类

import { storagePrefix } from 'assets/scripts/config/config'
import { verify, uri } from 'assets/scripts/tools'

/**
 * cookies操作类
 */
export default new class Cookie {
  /**
   * 构造函数
   */
  constructor() {
    this.defaults = {}
    this.expiresMultiplier = 60 * 60 * 24
    this.prefix = storagePrefix
  }

  /**
   * 根据key获取cookie的值
   * @param {string} key 键
   * @returns {object} 值
   */
  get(key) {
    if (!key) {
      throw new Error('没有找到key。')
    }
    if (typeof key === 'object') {
      throw new Error('key不能是一个对象。')
    }
    let cookies = this.all()
    let value = cookies[this.prefix + key]

    try {
      value = JSON.parse(value)
    } catch (e) {
      value = {}
    }
    return value
  }

  /**
   * 设置cookies
   * @param key 键
   * @param value 值
   * @param options 选项
   * @returns {Cookie}
   */
  set(key, value, options) {
    options = verify.isObject(options) ? options : {expires: options}
    let expires = options.expires !== undefined ? options.expires : (this.defaults.expires || '')
    let expiresType = typeof (expires)
    if (expiresType === 'string' && expires !== '') {
      expires = new Date(expires)
    } else if (expiresType === 'number') {
      expires = new Date(+new Date() + 1000 * this.expiresMultiplier * expires)
    }
    if (expires !== '' && 'toGMTString' in expires) {
      expires = ';expires=' + expires.toGMTString()
    }
    let path = options.path || this.defaults.path
    path = path ? ';path=' + path : ''
    let domain = options.domain || this.defaults.domain
    domain = domain ? ';domain=' + domain : ''
    let secure = options.secure || this.defaults.secure ? ';secure' : ''
    if (options.secure === false) secure = ''
    document.cookie = uri.encode(this.prefix + key) + '=' + uri.encode(JSON.stringify(value)) + expires + path + domain + secure
    return this
  }

  /**
   * 删除cookie
   * @param {string||array} keys 删除cookie的key
   * @returns {Cookie}
   */
  remove(keys) {
    keys = verify.isArray(keys) ? keys : [keys]
    for (let i = 0, l = keys.length; i < l; i++) {
      this.set(keys[i], '', -1)
    }
    return this
  }

  /**
   * 获取所有的cookie
   * @returns {object} cookie对象
   */
  all() {
    let cookie = document.cookie
    if (cookie === '') return {}
    let cookieArr = cookie.split('; ')
    let result = {}
    for (let i = 0, l = cookieArr.length; i < l; i++) {
      let item = cookieArr[i].split('=')
      let key = uri.decode(item.shift())
      let value = uri.decode(item.join(''))
      result[key] = value
    }
    return result
  }
}

verify 工具类

export default new class Verify {
  // 验证url是否正确,true/false
  isUrl (url) {
    return (/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?/i).test(url)
  }

  // 验证手机号码是否正确, true/false
  isTel (tel) {
    return (/^1[3|4|5|8][0-9]\d{4,8}$/).test(tel)
  }

  // 判断是否是object对象
  isObject (value) {
    return !!value && Object.prototype.toString.call(value) === '[object Object]'
  }

  // 判断是否是数组
  isArray (value) {
    return Object.prototype.toString.call(value) === '[object Array]'
  }
}

uri 工具类

export default new class Uri {
  decode (value) {
    return decodeURIComponent(value)
  }

  encode (value) {
    return encodeURIComponent(value)
  }
}

config 基础配置

// 本地存储的前缀
export const storagePrefix = 'tshark_quick_storage_'
上一篇:vuex 在非组件中调用 mutations 方法


下一篇:Vue 组件中监听路由变化