1、前言:
在vue中如果想要操作cookie,除了使用之前我们自己封装好的操作cookie的方法之外,我们还可以使用vue-cookies插件,这是一个简单的Vue.js插件,专门用于在vue中处理浏览器的cookie操作,vue-cookies没有依赖关系,它可以独立存在,对vuejs友好。本篇博文就来介绍如何使用vue-cookies插件。
2.安装vue-cookies
npm install vue-cookies --save
3.引入vue-cookies
安装完毕后,我们需要在vue项目中明确引入vue-cookies。
import Vue from 'vue'import VueCookies from 'vue-cookies'Vue.use(VueCookies)
4.API
-设置全局配置,设置cookie过期时间和url
this.$cookies.config(expireTimes[,path]) // default: expireTimes = 1d , path=/
-设置一个cookie
this.$cookies.set(keyName, value[, expireTimes[, path[, domain[, secure]]]]) //return this
-获取一个cookie
this.$cookies.get(keyName) // return value
-删除一个cookie
this.$cookies.remove(keyName [, path [, domain]]) // return this//例如:that.$cookies.remove("CHOOSE","/",'.xxx.com')
-检查某个 cookie name是否存在
this.$cookies.isKey(keyName) // return false or true
-获取所有 cookie name,以数组形式返回
this.$cookies.keys() // return a array
5.设置cookie过期时间
5.1全局设置
// 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')
5.2单个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);
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年后过期
6.其他操作
// set paththis.$cookies.set("use_path_argument","value","1d","/app"); // set domainthis.$cookies.set("use_path_argument","value",null, null, "domain.com"); // set securethis.$cookies.set("use_path_argument","value",null, null, null,true);
**遇到的问题
1、this.$cookies.get(‘CHOOSEJWTTOKEN’)为什么取不到值?重点排除一下:如果cookie中设置了HttpOnly,那么通过js脚本将无法读取cookie信息。(这样能有效的防止XSS攻击,窃取cookie内容,但即便这样,也不建议将重要的信息存入cookie。)
//使用vue-cookies操作cookie的部分code if(uni.getStorageSync('storage_token') == false){ if(this.$cookies.get('CHOOSEJWTTOKEN')){ uni.setStorageSync('storage_token', this.$cookies.get('CHOOSEJWTTOKEN')); } } //end