在vue中若是想要操做cookie,除了使用以前咱們本身封裝好的操做cookie的方法以外,咱們還能夠使用vue-cookies
插件,這是一個簡單的Vue.js插件,專門用於在vue中處理瀏覽器的cookie操做,vue-cookie
s沒有依賴關係,它能夠獨立存在,對vuejs友好。本篇博文就來介紹如何使用vue-cookies
插件。vue
npm install vue-cookies --save
安裝完畢後,咱們須要在vue項目中明確引入vue-cookies。npm
import Vue from 'vue' import VueCookies from 'vue-cookies' Vue.use(VueCookies)
-設置全局配置,設置cookie過時時間和url數組
this.$cookies.config(expireTimes[,path]) // default: expireTimes = 1d , path=/
-設置一個cookie瀏覽器
this.$cookies.set(keyName, value[, expireTimes[, path[, domain[, secure]]]]) //return this
-獲取一個cookiecookie
this.$cookies.get(keyName) // return value
-刪除一個cookiesession
this.$cookies.remove(keyName [, path [, domain]]) // return this
-檢查某個 cookie name是否存在app
this.$cookies.isKey(keyName) // return false or true
-獲取全部 cookie name,以數組形式返回dom
this.$cookies.keys() // return a array
5.1全局設置this
// 30天后過時 this.$cookies.config('30d') this.$cookies.config(new Date(2019,03,13).toUTCString()) this.$cookies.config(60 * 60 * 24 * 30,''); // window object window.$cookies.config('30d')
5.2單個name設置url
//不寫過時時間,默認爲1天過時 this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX") // 1天過時,忽略大小寫 this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX","1d") this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX","1D") // 以秒爲單位,設置1天過去 this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX",60 * 60 * 24) // 填寫Date對象,明確指定過時時間 this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX", new Date(2017, 03, 12)) // 填寫一個時間字符串,指定過時時間 this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX", "Sat, 13 Mar 2017 12:25:57 GMT") //瀏覽器會話結束時過時 this.$cookies.set("default_unit_second","input_value","0"); //永不過時 this.$cookies.set("default_unit_second","input_value",-1);
5.3字符串單位形式設置
設置過時時間,輸入字符串類型(字符均忽略大小寫):
Unit | full name |
---|---|
y | year |
m | month |
d | day |
h | hour |
min | minute |
s | second |
this.$cookies.set("token","GH1.1.1689020474.1484362313","60s"); // 60秒後過去 this.$cookies.set("token","GH1.1.1689020474.1484362313","30MIN"); // 30分鐘後過去 this.$cookies.set("token","GH1.1.1689020474.1484362313","24d"); // 24天后過時 this.$cookies.set("token","GH1.1.1689020474.1484362313","4m"); // 4個月後過時 this.$cookies.set("token","GH1.1.1689020474.1484362313","16h"); // 16小時後過時 this.$cookies.set("token","GH1.1.1689020474.1484362313","3y"); // 3年後過時
// set path this.$cookies.set("use_path_argument","value","1d","/app"); // set domain this.$cookies.set("use_path_argument","value",null, null, "domain.com"); // set secure this.$cookies.set("use_path_argument","value",null, null, null,true);
(完)