vue-cookies
vue-cookies用于登录,一般和vuex一起使用
vuex在各个组件共享值,cookie恒久保留值
一、安装
npm install vue-cookies --save
二、引用(在store.js文件中)
import Vue from 'Vue' import VueCookies from 'vue-cookies' Vue.use(VueCookies)
三、操作
1、设置
this.$cookies.set(keyName,赋予keyname的值 ,time)
2、获取
this.$cookies.get(keyName) // return value
3、删除
this.$cookies.remove(keyName) // return false or true , warning: next version return this; use isKey(keyname) return true/false,please
4、查看cookie是否存在
this.$cookies.isKey(keyName) // return false or true
5、获取所有cookie
this.$cookies.keys() // return a array
6、例子
import Vue from 'vue' import Vuex from 'vuex' import Cookies from 'vue-cookies' Vue.use(Vuex); export default new Vuex.Store({ // 一旦刷新,cookie没有更新,但全局变量state丢失,所有state的命令应该从cookie中取 state: { username: Cookies.get('username'), token: Cookies.get('token') }, mutations: { // userToken保存username 和token,user 和 token保存到内存,并保存到cookie(Vue是单页面应用,一旦刷新,内存消失) saveToken (state, userToken) { state.token = userToken.token; state.username =userToken.username; Cookies.set('username', userToken.username, '20min') Cookies.set('token', userToken.token, '20min') }, // 清除内存和cookie clearToken (state){ state.username = null; state.token = null; Cookies.remove('username'); Cookies.remove('token'); } } })