Vue中 引入使用 js-cookie

1. js-cookie 安装及引入

js-cookie 是关于 cookie 存储的一个js的API,根据官网描述其优点有:适用所有浏览器、接受任何字符、经过任何测试没什么 bug、支持 CMD 和 CommonJS、压缩之后非常小,仅900个字节。

js-cookie npm地址

npm install js-cookie --save

全局引入 (本文第2点以下均以全局引入为例)

// main.js
import jsCookie from 'js-cookie'
Vue.prototype.$cookie = jsCookie;  // 在页面里可直接用 this.$cookie 调用

按需引入

// http.js
import Cookies from 'js-cookie';

Cookies.set('key', 'value');
console.log(Cookies.get('key')); // value

2. 存储(设置) cookie

this.$cookie.set('key', 'value');

// 为 /about 路径设置了一个有效期为 7 天的cookie
this.$cookie.set('name', 'about', {
    
     expires: 7});

如上, 第三个参数是个对象, 可设置需要的 cookie 的属性

expires : 定义有效期。如传入Number,则单位为天,也可传入一个Date对象,表示有效期至Date指定时间。默认情况下cookie有效期截止至用户退出浏览器。
path : string,表示此 cookie 对哪个地址可见。默认为”/”。
domain : string,表示此 cookie 对哪个域名可见。设置后 cookie 会对所有子域名可见。默认为对创建此 cookie 的域名和子域名可见。
secure : truefalse,表示 cookie 传输是否仅支持 https。默认为不要求协议必须为 https。

3. 获取 cookie

// 获得某个cookie
this.$cookie.get('key'); // value

// 获得所有的cookie
this.$cookie.get(); // { key: "value", name: "about"}

// 获得 xxx.xxxx.com 域下的 cookie
this.$cookie.get('name', {
    
     domain: 'xxx.xxxx.com' })

4. 删除 cookie

this.$cookie.remove('key');

// 如果值设置了路径,则不能用简单的 remove 方法删除值,需在 remove 时指定路径
this.$cookie.set('id', '123456', {
    
     path: '' });
this.$cookie.remove('id');  // 删除失败
this.$cookie.remove('id', {
    
     path: '' });  // 删除成功

注意 : 删除不存在的 cookie 不会报错也不会有返回。

5. JSON 用法

cookie 一般只保存 string, 当传入 Array 或对象,而不是简单的 string,那么 js-cookie 会将你传入的数据用 JSON.stringify 悄悄地转换为 string 保存。

this.$cookie.set('name', {
    
     key1: 'value1' });
console.log( JSON.parse(this.$cookie.get('name')) ); // { key1: "value1"}
console.log( this.$cookie.get() ); // { name: '{"key1":"value1"}' }

也可用 getJSON 获取 cookie,则 js-cookie 会用 JSON.parse 解析 string 并返回。

this.$cookie.set('name', {
    
     key1: 'value1' });
console.log( this.$cookie.getJSON('name') ); // { key1 : "value1" }
console.log( this.$cookie.getJSON() ); // { name: { key1 :"value1" } }

6. 自定义覆盖

通过 withConverter 方法可以覆写默认的 decode 实现,并返回一个新的 cookie 实例。
所有与 decode 有关的 get 操作,如:Cookies.get() 或 Cookies.get(‘name’) 都会先执行此方法中的代码。

document.cookie = 'escaped=%u5317';
document.cookie = 'default=%E5%8C%97';

let cookiesNew = this.$cookie.withConverter((value, name) => {
    
    
  if ( name === 'escaped' ) {
    
    
    return unescape(value);
  }
});
console.log( cookiesNew .get('escaped') ); // 北
console.log( cookiesNew .get('default') ); // 北
console.log( cookiesNew .get() ); // { escaped: '北', default: '北' }

通过 withConverter 方法也可以覆写默认的 encode 实现,并返回一个新的 cookie 实例。

this.$cookie.withConverter({
    
    
  read: function (value, name) {
    
    
    // Read converter
  },
  write: function (value, name) {
    
    
    // Write converter
  }
});

Supongo que te gusta

Origin blog.csdn.net/ZYS10000/article/details/116245691
Recomendado
Clasificación