vue封裝cookie及使用


直接拷貝過去就能直接使用,無需改動

我在我的項目文件assets中新建了一個tool.js的文件用來存放公共的方法

 

1、tool.js的文件內容如下

/**
 * @author xxxx
 * @description 保存cookie
 * @param {String} name 需要存儲cookie的key
 * @param {String} value 需要存儲cookie的value
 * @param {Number} timer 默認存儲多少天
 */
function setCookie(name,value,timer=1){
  var Days = timer; //默認將被保存 1 天
  var exp  = new Date();
  exp.setTime(exp.getTime() + Days*24*60*60*1000);
  document.cookie = name + "="+ escape(value) +";expires="+ exp.toGMTString();
}

/**
 * @author xxxx
 * @description 獲取cookie
 * @param {String} name 需要獲取cookie的key
 */
function getCookie(name){
  var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
  if(arr != null){
    return unescape(arr[2])
  }else{
    return null
  }
}

/**
 * @author xxxx
 * @description 刪除cookie
 * @param {String} name 需要刪除cookie的key
 */
function clearCookie(name){
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval=getCookie(name);
  if(cval!=null) document.cookie=name +"="+cval+";expires="+exp.toGMTString();
}

export default {
  setCookie,
  getCookie,
  clearCookie
}

2、在mian.js文件中引入tool.js並掛載到vue原型上

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false

import tool from './assets/js/tool'
Vue.prototype.tool = tool;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

3、使用:在需要存儲,讀取,刪除cookie的頁面中

// 存儲cookie
this.tool.setCookie('sessionId',res.result.sessionId)
// 取出cookie
console.log(this.tool.getCookie('sessionId'))
// 刪除cookie
setTimeout(()=>{
  等待三秒后再刪除   
this.tool.clearCookie('sessionId') },3000)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM