好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

前端Vue设置cookie、删除cookie,获取cookie方式

Vue设置cookie、删除cookie、获取cookie

在main.js中如下设置

设置cookie

Vue.prototype.Setcookie = function (name,value) {
? //设置名称为name,值为value的Cookie
? var expdate = new Date(); ? //初始化时间
? expdate.setTime(expdate.getTime() + 30 * 60 * 1000); ? //时间单位毫秒
? document.cookie = name + "=" + escape(value) + ";expires=" + expdate.toGMTString() + ";path=/";
? //即document.cookie= name+"="+value+";path=/"; ?时间默认为当前会话可以不要,但路径要填写,因为JS的默认路径是当前页,如果不填,此cookie只在当前页面生效!
}

获取cookie

Vue.prototype.getcookie = function (a){
? // console.log(a)
? var d;
? var b = document.cookie;
? // console.log(b)
? var c = b.split(";");
? for (let e = 0; e < c.length; e++) {
? ? var f = c[e].split("=");
? ? if (a == f[0].toString().trim()) {
? ? ? d = f[1];
? ? ? break;
? ? }
? } if (void 0 == d || null == d) {
? ? return "";
? }
? else {
? ? var g = unescape(d.trim());
? ? return g;
? }
}

删除cookie

Vue.prototype.delCookie= function (a){
? ? ? var b = new Date(0).toGMTString();
? ? ? document.cookie = a + "=;expires=" + b + ";path=/";
? ? },

Vue允许跨域携带cookie

import axios from 'axios'
axios.defaults.withCredentials = true;// 允许跨域携带cookie

或者在请求拦截器中添加

config.headers['Access-Control-Allow-Credentials']=true

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

查看更多关于前端Vue设置cookie、删除cookie,获取cookie方式的详细内容...

  阅读:59次