1. 程式人生 > >vue設定cookie的方法封裝

vue設定cookie的方法封裝

common.js

//設定cookie,增加到vue例項方便全域性呼叫
  setCookie:(c_name, value, expiredays) => {
		var exdate = new Date();
		exdate.setDate(exdate.getDate() + expiredays);
		document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
	},
	
//獲取cookie、
  getCookie: name => {
		var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
		if (arr = document.cookie.match(reg))
			return (arr[2]);
		else
			return null;
	},
	
//刪除cookie
  delCookie: name => {
		var exp = new Date();
		exp.setTime(exp.getTime() - 1);
		var cval = getCookie(name);
		if (cval != null)
		 document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
	}

main.js中引入,掛載到vue原型上

import common from '../static/js/common'
Vue.prototype.common = common

元件中引用

 this.common.setCookie("token",'111111111111');//快取token
 console.log('獲取cookie',this.common.getCookie("token"));//獲取快取的token