vue資源庫中有個插件很好用vue-cookies
github地址:https://github.com/cmp-cc/vue-cookies
使用起來也很方便,將vue-cookies.js 引入
$cookies.config() 設置默認值
this.$cookies.config(expireTimes, path)
expireTimes 默認1d
path 默認'/',
$cookies.set()
this.$cookies.set(key, value[, expireTimes[, path[, domain[, secure]]]])
- key: cookie名
注意 $cookies key names Cannot be set to ['expires', 'max-age', 'path', 'domain', 'secure']- value: cookie值
vue-cookie會自動幫你把對象轉為json if (value && value.constructor === Object ){value = JSON.stringify(value)}- expireTimes: cookie有效時間,默認時間為1d
可以為到期時間點,也可以為有效時間段,在vue-cookies中傳入Infinity||-1被認該cookie永久有效,傳入'0'則關閉瀏覽器的時候銷毀cookie- path: cookie所在目錄,默認 '/' 根目錄
設置path: '/projectName/'指定項目名下'/projectName/'使用- domain: cookie所在的域,默認為請求地址
- secure: Secure屬性是說如果一個cookie被設置了Secure=true,那么這個cookie只能用https協議發送給服務器,用http協議不發送。
$cookies.get('key')
this.$cookies.get(key) // return value
$cookies.remove('key')
this.$cookies.remove(key [, path [, domain]]) // return false or true , warning: next version return this; use isKey(key) return true/false,please
是否有key cookie
this.$cookies.isKey(key) // return true or false
列出所有cookie
this.$cookies.keys() // return ['key', 'key', ......]