欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue项目封装一个cookie

程序员文章站 2024-03-20 14:20:58
...
const cookies =  {

  //设置cookie
  set(key , value , dutation = 60 * 1000){
    const date  = new Date().getTime() +  dutation * 1000
    const _key = key.trim()
    const _value = value.toString().trim()
    document.cookie = _key + '=' + _value + ';expires=' + new Date(date).toUTCString();
  },

  //获取cookie
  get(key){

    if(document.cookie === '') return "" ;

    let obj = {};        //最终获得所有的cookie对象
    let cookiesArr = []; // 分割cookies字符串

    cookiesArr = document.cookie.split(';');
    for(let value of cookiesArr){
      const item =  value.split('=');
      obj[item[0].trim()] = item[1].trim()
    }

    if(key){
      const _key = key.trim()
      return obj[_key]
    }else{
      return obj
    }

  },

  //删除cookie
  remove(key){
    const _key = key.trim();
    const date = new Date().getTime() - 1;
    document.cookie = _key + '=;expires=' + new Date(date).toUTCString();
  }

}

export default cookies

最后在main.js文件中引入模块并挂载到vue中
import cookies from '@/utils/cookiesjs'
Vue.prototype.$cookies = cookies