How to use js-cookie in Vue
Editor to share with you how to use js-cookie in Vue, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
First, install js-cookiecnpm I-S js- cookie II, use 1, use import Cookies from "js-cookie" locally
Example:
Current token: {{token}}
GetToken setToken removeToken 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")}}
Effect:
If you want to set the validity period, you can add the expires attribute, in days. That is:
SetToken (token) {Cookies.set ("token", token, {expires: 7}); / / valid for 7 days}
Get all Cookie functions: Cookies.get ()
2. Global use
Introduced into main.js:
Import Cookies from "js-cookie"; Vue.prototype.$cookie = Cookies
Use:
Current token: {{token}}
GetToken setToken removeToken export default {data () {return {token: ", allCookies:"};}, methods: {getToken () {this.token = this.$cookie.get ("token");}, setToken (token) {this.$cookie.set ("token", token, {expires: 7}) / / valid for 7 days}, removeToken () {this.$cookie.remove ("token");}
Note: when using js-cookie globally, the removeToken function here does not use the arrow function, but the ordinary function.
The above is all the content of the article "how to use js-cookie in Vue". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!