Vue使用js-cookie
~疆 人气:0一、安装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
函数就不要用箭头函数了,就用普通的函数写法
加载全部内容