两种方式 存取删读cookie
第一种
//存cookies
例如:this.setCookie(‘authorization’, JSON.stringify({authorization: res.data.content}), 1)
//第一个参数是 cookie名字 第二个是cookie的值 第三个就是cookie存在的时间
Vue.prototype.setCookie = function (name, value, day) {
if (day) { //如果当前给cookie设置了时间
var exp = new Date();
exp.setTime(exp.getTime() + day * 24 * 60 * 60 * 1000);
document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
}
else {
document.cookie = name + "=" + escape(value) + ';path=/';
}
}
// 取cookies
Vue.prototype.getCookie = function (name) {
var arr,
reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if ((arr = document.cookie.match(reg))) return unescape(arr[2]);
else return null;
}
// 删除cookies
Vue.prototype.delCookie = function (name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1000);
var cval = this.getCookie(name);
if (cval != null)
document.cookie = name + "=" + cval + ";path=/;expires=" + exp.toGMTString();
}
//读cookies 登录验证的时候需要获取的cookie
Vue.prototype.getAuthorization = function () {
if(this.getCookie('authorization')){
return JSON.parse(this.getCookie('authorization')).authorization
}else {
this.$router.push({ path: '/Login' });
return;
}
第二种
//第一个参数是 cookie名字 第二个是cookie的值 第三个就是cookie存在的时间
Vue.prototype.setCookie = function (key, value, days) {
// 设置过期原则
if (!value) {
localStorage.removeItem(key)
} else {
var Days = days || 1; // 默认保留1天
var exp = new Date();
localStorage[key] = JSON.stringify({
value,
expires: exp.getTime() + Days * 24 * 60 * 60 * 1000
})
}
}
//读取cookies
Vue.prototype.getCookie = function (name) {
try {
let o = JSON.parse(localStorage[name])
if (!o || o.expires < Date.now()) {
return null
} else {
return o.value
}
} catch (e) {
// 兼容其他localstorage
// console.log(e)
return localStorage[name]
} finally {
}
}
//删除cookies
Vue.prototype.delCookie = function (key) {
localStorage.removeItem(key)
}
// 读token
Vue.prototype.getToken = function () {
var that = this;
var authorization
if(this.getCookie('gateway_token')){
authorization = this.getCookie('gateway_token');
}else{
authorization = null
};
//如果token失效重新获取
if (authorization == null) {
$.ajax({
url: that.GLOBAL.url + "auth/token?username=jingzhun&password=360fob",
type: "GET",
async: false,
success: function (data) {
if (data.status == 1 && data.message == 'SUCCESS') {
authorization = "Bearer " + data.content;
//保存6小时
that.setCookie('gateway_token', authorization, 1);
} else {
that.$message({
message: that.$t('messages.getTokenFailed'),
type: "error",
customClass: "base-message-zindex"
});
}
},
error: function () {
that.$message({
message: that.$t('messages.erverException'),
type: "error",
customClass: "base-message-zindex"
});
}
});
}
return authorization;
}
个人建议第一种方法,但是前提是你登录的接口不需要cookie验证只需要账号密码 而cookie是在登录成功的时候 接口返回的