在Vue2.0项目中与H5项目中获取、设置、清除cookie的一些注意点

1,760 阅读1分钟

在vue中获取cookie

原生js方法没有直接获取cookie中值的,所以我在vue的项目中我自己写了个获取cookie值的方法(还有删除与设置cookie的方法还没去写,大家一起来补充完善)

    <!-- 在使用的页面中 -->
     methods: { 
        getCookieVal(key) { 
          if (document.cookie.length === 0) return
          const cookieConfig = new Map()
          document.cookie.split('; ').map((item)=>{
              const itemArr = item.split('=')
              cookieConfig.set(itemArr[0],itemArr[1])
          })
          return cookieConfig.get(key)     
        }
    }
    <!-- 在utils中 -->
    const getCookieVal = (key) =>{ 
          if (document.cookie.length === 0) return
          const cookieConfig = new Map()
          document.cookie.split('; ').map((item)=>{
              const itemArr = item.split('=')
              cookieConfig.set(itemArr[0],itemArr[1])
          })
          return cookieConfig.get(key)     
    }
    module.exports = {
        otherMethods...
        getCookieVal, // 新增入方法
    }
    <!-- 在需要使用的页面引入 -->
    import { getCookieVal ,otherMethods...} from '@/utils'
    

(ps:这个方法只能获取同一个作用域下的cookie的值,关于cookie作用域的注意点下面会写)

在vue中设置、清除cookie

    <!-- 获取cookie -->
    const cookieVal = this.getCookieVal('keyName') 
    <!-- 设置cookie -->
    document.cookie = `${keyName}=${keyValue};path=/;expires=7`;
    <!-- 清除cookie  -->
    document.cookie = `${keyName}=;  expires=Thu, 01 Jan 1970 00:00:01` GMT;`(设置过期时间小于当前时间则会被浏览器清除)

(tips:path设置为整个主域/,不设置的话在其他页面获取时候会undefined )

h5项目中使用JQ对cookie进行操作

    <!-- 设置(写入) -->
    $.cookie('keyName', 'keyValue', { domain:'qq.com', path: '/',expires: 7 });
    ( expires属性设置过期时间;path属性设置作用域)
    <!-- 获取(读取) -->
    $.cookie('keyName')
    <!-- 清除(重置) -->
    $.cookie("keyName", null, { path: "/" }); // 这是个坑 (实际上不设置后keyValue变为字符串'null',不建议)
    
    建议使用一下两种方法
    $.removeCookie('keyName',{ path: '/'});
    $.cookie('keyName','',{ path: '/' })