在vue中通常使用axios进项http请求,但是axios不带cookie,这里可自己获取cookie,放到参数中进行登录验证等,方法不唯一。
cookie.js
/**
* 读取cookie,
* 需要注意的是cookie是不能存中文的,如果需要存中文,解决方法是后端先进行编码encode(),
* 前端取出来之后用decodeURI('string')解码。(安卓可以取中文cookie,IOS不行)
* */
export const b_getCookie = (c_name) => {
var name = c_name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) != -1) {
return c.substring(name.length, c.length);
}
}
return "";
}
/**
* 设置cookie
* c_name: cookie的名字,
* value : cookie值,
* expiredays: 过期时间(天数)
* */
export const b_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
* c_name: cookie的名字,
* */
export const b_delCookie = (c_name) => {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = getCookie(c_name);
if (cval != null)
document.cookie = c_name + "=" + cval + ";expires=" + exp.toGMTString();
}
<template>
<div>
<el-row>
<el-input v-model="input" placeholder="请输入内容"></el-input>
<el-button @click="getCookie">获取cookie</el-button>
<el-button @click="setCookie">设置cookie</el-button>
</el-row>
</div>
</template>
<script>
import {b_getCookie, b_setCookie} from "../utils/cookie";
export default {
name: "Test",
data() {
return {
input: ''
}
},
methods: {
getCookie() {
console.log("==========获取cookie===========")
let username = b_getCookie("username")
let password = b_getCookie("password")
console.log(username);
console.log(password);
},
setCookie() {
console.log("设置cookie");
b_setCookie("c_key", "c_value", 30)
}
}
}
</script>
<style scoped>
</style>
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://vitcloud.blog.csdn.net/article/details/122972850
内容来源于网络,如有侵权,请联系作者删除!