Use of js-cookies

1. Download js-cookie

npm install js-cookie

2. Introduce js-cookie

import Cookies from "js-cookie";

3. Use

// 写入cookie
Cookies.set('name', 'value')
// 读取
Cookies.get('name') // => 'value'
Cookies.get('nothing') // => undefined
// 读取所有可见的cookie
Cookies.get()
// 删除某项cookie值
Cookies.remove('name')

4. Cookies are used globally (method 2) introduced in main.js

import Cookies from 'js-cookie'

5. Cookie setting expiration time

//1、存cookie  set方法支持的属性有 :  expires->过期时间    path->设置为指定页面创建cookie   domain-》设置对指定域名及指定域名的子域名可见  secure->值有false和true ,表示设置是否只支持https,默认是false
Cookies.set('key', 'value');  //创建简单的cookie
Cookies.set('key', 'value', { expires: 27 });//创建有效期为27天的cookie
Cookies.set('key', 'value', { expires: 17, path: ''  }); //可以通过配置path,为当前页创建有效期7天的cookie

//2、取cookie
Cookies.get('key'); // 获取指定key 对应的value
Cookies.get(); //获取所有value

//3、删除cookie
Cookies.remove('key');//删除普通的cookie
Cookies.remove('name', { path: '' }); // 删除存了指定页面path的cookie
注意:如果存的是对象,如: userInfo = {age:111,score:90};  Cookie.set('userInfo',userInfo)

取出来的userInfo需要进行JSON的解析,解析为对象:let res = JSON.parse( Cookie.get('userInfo') );

当然你也可以使用:Cookie.getJSON('userInfo');
Cookies.get('name'); // => '{"foo":"bar"}'
Cookies.get(); // => { name: '{"foo":"bar"}' }
//-------------------------------------------------------//
Cookies.getJSON('name'); // => { foo: 'bar' }
Cookies.getJSON(); // => { name: { foo: 'bar' } }

Requirements: In the business development, the business needs to cache data at the front end, delete it when it expires, and then obtain new data.

There are two ways to set the timed expiration of the data on the front end:
1. When the data is large, you can use localstorage to write a time when saving the data, and compare it with the current time when you get it. 2.
If the data does not exceed the cookie To limit the size, it is more convenient to use cookies, just set the validity period directly.

Using localstorage to achieve: steps

1. Add timestamp when storing data
In project development, we can write a public method to add timestamp when storing

//export抛出
export function setLocalStorageAndTime (key, value) {
 window.localStorage.setItem(key, JSON.stringify({ data: value, time: new Date().getTime() }))
}

project

storage

// 有数据再进行存储
  setLocalStorageAndTime('XXX', {name: 'XXX'})

read

// 判断是否返回为null或者失效
getLocalStorageAndTime('XXX', 86400000)

Compare with the current time when fetching data

export function getLocalStorageAndTime (key, exp = 86400000) {
 // 获取数据
 let data = window.localStorage.getItem(key)
 if (!data) return null
 let dataObj = JSON.parse(data)
 // 与过期时间比较
 if (new Date().getTime() - dataObj.time > exp) {
  // 过期删除返回null
  removeLocalStorage(key)
  console.log('信息已过期')
  return null
 } else {
  return dataObj.data
 }
}

Use cookies to achieve

The js-cookie example only has an expiration date in days:

Cookies.set('name', 'value', { expires: 7 }); // 7 天后失效

Official documents only need to set the number of days, not hours, minutes and seconds, so we can’t do it when we want to set a smaller unit. In fact, we can also set a timestamp to process time. The following method can set the validity period of any unit:

let seconds = 10;
let expires = new Date(new Date() * 1 + seconds * 1000);
Cookies.set('username', 'tanggaowei', { expires: expires }); // 10 秒后失效

Paste the secondary package using js-cookie, remember npm i js-cookie

import Cookies from 'js-cookie'
 
/*
* 设置cookies
* */
export function getCookies (key) {
 return Cookies.get(key)
}
/*
* 设置Cookies
* */
export function setCookies (key, value, expiresTime) {
 let seconds = expiresTime
 let expires = new Date(new Date() * 1 + seconds * 1000)
 return Cookies.set(key, value, { expires: expires })
}
/*
* 移除Cookies
* */
export function removeCookies (key) {
 return Cookies.remove(key)
}

Domain domain and path
default value:
path: '/'

domain indicates the domain where the cookie is located, and the default is the requested address, such as www.jb51.net/test/test.aspx , then the default domain is www.jb51.net . For cross-domain access, if domain A is t1.test.com , and domain B is t2.test.com , then to produce a cookie in domain A that can be accessed by both domain A and domain B, the domain of the cookie must be set to .test.com ; If you want to generate a cookie in domain A that domain A cannot access but domain B can access, you must set the domain of the cookie to t2.test.com .

path indicates the directory where the cookie is located, asp.net defaults to /, which is the root directory. There are directories on the same server as follows: /test/, /test/cd/, /test/dd/, now set the path of cookie1 as /test/, and the path of cookie2 as /test/cd/, then the path under test All pages can access cookie1, while subpages of /test/ and /test/dd/ cannot access cookie2. This is because the cookie allows pages under its path to be accessed.

cookie.set() more parameters
syntax:
cookies.set(name, [value], [options])
more options parameter configuration:

maxAge: a number representing the number of milliseconds since Date.now() expires

expires: A Date object indicating the expiration date of the cookie (expires at the end of the session by default). Default: days

path: A string indicating the path of the cookie (/ by default).

domain: A string indicating the domain of the cookie (no default).

secure: A boolean indicating whether the cookie is only sent over HTTPS (false by default for HTTP, true by default for HTTPS). Read more about this option below.
httpOnly: A boolean indicating whether the cookie is only sent over HTTP(S) and not served to client JavaScript (true by default).

sameSite: boolean or string indicating that the cookie is a "same site" cookie (false by default). It can be set to 'strict', 'lax' or true (maps to 'strict').

signed: A boolean indicating whether the cookie is to be signed (false by default). If true, .sig will also send another cookie of the same name with a suffix whose 27-byte url-safe base64 SHA1 value represents the hash of cookie-name=cookie-value against the first Keygrip key. This signing key is used to detect tampering the next time the cookie is received.

overwrite: A boolean indicating whether to overwrite a previously set cookie of the same name (false by default). If so, all cookies set in the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when this cookie is set.

おすすめ

転載: blog.csdn.net/weixin_52615140/article/details/128543259