今天分享一个cookie小应用:如何使用vue-cookies的技巧。
前端设置cookie之vue-cookies {#heading-0}
{#_lab2_0_0}
安装vue-cookies {#heading-1}
npm i vue-cookies --save
引入vue-cookies {#heading-2}
import VueCookies from ``'vue-cookies'``;
Vue.use(VueCookies)
Api {#heading-3}
设置一个cookie
this.$cookies.set("token", value1, {expires: "7D"});
// keyName => "token"
// value => value1
// 设置过期时间 = > {expires: "7D"}
获取一个cookie:
this.$cookies.get(keyName) // return value
删除一个cookie:
this.$cookies.remove(keyName [, path [, domain]]) // return this
检查某个 cookie name是否存在:
this.$cookies.isKey(keyName) // return false or true
获取所有 cookie name,以数组形式返回:
this.$cookies.keys() // return a array
设置cookie过期时间:
全局设置:
// 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')
单个name设置:
//不写过期时间,默认为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);
vue的cookies:vue-cookies设置,获取及删除指定的cookies {#heading-4}
安装:
npm install vue-cookies --save
引用:
main.js中设置
// vue-cookies配置
import cookies from 'vue-cookies'
Vue.prototype.$cookies = cookies;
vue-cookie使用 {#heading-5}
1、设置cookie
this.$cookies.set(keyName, value[, expireTimes[, path[, domain[, secure]]]]) //return this
// 简洁使用
this.$cookies.set('key','value', '过期时间,按秒计');
// 示例
this.$cookies.set('username',response.data.username, '张三');
2、获取cookie
this.$cookies.get(keyName) // return value
3、删除cookie
this.$cookies.remove(keyName);
4、判断cookie中是否有指定的key
this.$cookies.isKey(keyName)
5、获取所有cookie
this.$cookies.keys()