前端设置cookie之vue-cookies使用介绍
目录
-
前端设置cookie之vue-cookies
-
安装vue-cookies
-
引入vue-cookies
-
Api
-
-
vue的cookies:vue-cookies设置,获取及删除指定的cookies
-
vue-cookie使用
-
-
总结
前端设置cookie之vue-cookies
安装vue-cookies
npm i vue-cookies --save
引入vue-cookies
import VueCookies from 'vue-cookies';Vue.use(VueCookies)
Api
设置一个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 objectwindow.$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
安装:
npm install vue-cookies --save
引用:
main.js中设置
// vue-cookies配置import cookies from 'vue-cookies'Vue.prototype.$cookies = cookies;
vue-cookie使用
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()