Vue项目实操cookie相关操作封装
生活随笔
收集整理的这篇文章主要介绍了
Vue项目实操cookie相关操作封装
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
文章目录
- 1 介绍
- 2 utils
- 3 Test.vue
1 介绍
在vue中通常使用axios进项http请求,但是axios不带cookie,这里可自己获取cookie,放到参数中进行登录验证等,方法不唯一。
2 utils
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(); }3 Test.vue
<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>总结
以上是生活随笔为你收集整理的Vue项目实操cookie相关操作封装的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 渗透测试---数据库安全: sql注入数
- 下一篇: Vue.2.0.5-模板语法