在Vue2.0项目中与H5项目中获取、设置、清除cookie的一些注意点
生活随笔
收集整理的這篇文章主要介紹了
在Vue2.0项目中与H5项目中获取、设置、清除cookie的一些注意点
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在vue中獲取cookie
原生js方法沒有直接獲取cookie中值的,所以我在vue的項目中我自己寫了個獲取cookie值的方法(還有刪除與設置cookie的方法還沒去寫,大家一起來補充完善)
<!-- 在使用的頁面中 -->methods: { getCookieVal(key) { if (document.cookie.length === 0) returnconst 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) returnconst 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: '/' })復制代碼轉載于:https://juejin.im/post/5c10560df265da6135726db0
總結
以上是生活随笔為你收集整理的在Vue2.0项目中与H5项目中获取、设置、清除cookie的一些注意点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 表单验证失败提示方案(自用)
- 下一篇: 移动前端开发之viewport,devi