一、安装js-cookie
cnpm i -S js-cookie
二、使用
1、局部使用
import Cookies from "js-cookie";
示例:
<template> <div> <p>当前token: {{token}}</p> <el-button @click="getToken()">getToken</el-button> <el-button @click="setToken('asdfasasf暗室逢灯fdasdf')">setToken</el-button> <el-button @click="removeToken()">removeToken</el-button> </div> </template> <script> import Cookies from "js-cookie"; export default { components: {}, data() { return { token: "" }; }, methods: { getToken() { this.token = Cookies.get("token"); }, setToken(token) { Cookies.set("token", token); }, removeToken: () => Cookies.remove("token") } }; </script>
效果:
如果想要设置有效期,添加expires属性即可,单位为天。即:
setToken(token) { Cookies.set("token", token, { expires: 7 }); //有效期为7天 }
获取所有Cookie函数:Cookies.get();
2、全局使用
main.js中引入:
import Cookies from "js-cookie"; Vue.prototype.$cookie = Cookies;
使用:
<template> <div> <p>当前token: {{token}}</p> <el-button @click="getToken()">getToken</el-button> <el-button @click="setToken('asdfasasf暗室逢灯fdasdf')">setToken</el-button> <el-button @click="removeToken()">removeToken</el-button> </div> </template> <script> export default { data() { return { token: "", allCookies: "" }; }, methods: { getToken() { this.token = this.$cookie.get("token"); }, setToken(token) { this.$cookie.set("token", token, { expires: 7 }); //有效期为7天 }, removeToken() { this.$cookie.remove("token"); } } }; </script>
注意:全局使用js-cookie
时,这里的removeToken
函数就不要用箭头函数了,就用普通的函数写法
到此这篇关于Vue中使用js-cookie详情的文章就介绍到这了,更多相关Vue使用js-cookie内容请搜索阿兔在线工具以前的文章或继续浏览下面的相关文章希望大家以后多多支持阿兔在线工具!