# 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]) |
- 设置一个 cookie
| this.$cookies.set(keyName, value[, expireTimes[, path[, domain[, secure]]]]) |
- 获取一个 cookie
| this.$cookies.get(keyName) |
- 删除一个 cookie
| this.$cookies.remove(keyName [, path [, domain]]) |
- 检查某个 cookie name 是否存在
| this.$cookies.isKey(keyName) |
- 获取所有 cookie name,以数组形式返回
# 5. 设置 cookie 过期时间
# 5.1 全局设置
| |
| this.$cookies.config('30d') |
| |
| this.$cookies.config(new Date(2019,03,13).toUTCString()) |
| |
| this.$cookies.config(60 * 60 * 24 * 30,''); |
| |
| |
| window.$cookies.config('30d') |
# 5.2 单个 name 设置
| |
| this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX") |
| |
| |
| this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX","1d") |
| this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX","1D") |
| |
| |
| this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX",60 * 60 * 24) |
| |
| |
| 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"); |
| |
| this.$cookies.set("token","GH1.1.1689020474.1484362313","30MIN"); |
| |
| this.$cookies.set("token","GH1.1.1689020474.1484362313","24d"); |
| |
| this.$cookies.set("token","GH1.1.1689020474.1484362313","4m"); |
| |
| this.$cookies.set("token","GH1.1.1689020474.1484362313","16h"); |
| |
| this.$cookies.set("token","GH1.1.1689020474.1484362313","3y"); |
# 6. 其他操作
| |
| this.$cookies.set("use_path_argument","value","1d","/app"); |
| |
| |
| this.$cookies.set("use_path_argument","value",null, null, "domain.com"); |
| |
| |
| this.$cookies.set("use_path_argument","value",null, null, null,true); |