拨云见日
本篇文章主要是介绍在客户端如何操作cookie
一、安装
npm安装
npm install js-cookie --save
切换到淘宝镜像源
cnpm install js-cookie --save
yarn安装
yarn add js-cookie --save
项目引用
common引用
const Cookie = process.client ? require("js-cookie") : undefined;
es6引用
import Cookies from 'js-cookie'
项目中使用
cookie存储
// Create a cookie, valid across the entire site:
//创建一个cookie 全站点使用
Cookies.set('name', 'value');
// Create a cookie that expires 10days from now, valid across the entire site:
//创建一个cookie,从现在起7天过期,在整个站点有效:
Cookies.set('name', 'value', { expires: 10 });
// Create an expiring cookie, valid to the path of the current page:
//创建一个过期的cookie,对当前页面的路径有效:
Cookies.set('name', 'value', { expires: 7, path: '' });
取出cookie
// Read cookie:
//读取cookie
Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined
// Read all visible cookies:
//读取所有cookie
Cookies.get(); // => { name: 'value' }
删除cookie
// Delete cookie:
//删除指定cookie
Cookies.remove('name');
// Delete a cookie valid to the path of the current page:
//删除对当前页面路径有效的cookie:
Cookies.set('name', 'value', { path: '' });
Cookies.remove('name'); // fail!
Cookies.remove('name', { path: '' }); // removed!
特殊使用
在Cookie中存对象,跟一般使用不同的是,从Cookie中取出的时候,要从字符串转换成json格式
const user = {
name: 'lia',
age: 18} ;
Cookies.set('user', user)
const liaUser = JSON.parse(Cookies.get('user'))
// Create a cookie, valid across the entire site:
//创建一个在整个站点都有效的cookie
Cookies.set('name', 'value');
// Create a cookie that expires 7 days from now, valid across the entire site:
//创建一个cookie,过期7天从现在起,有效的整个网站:
Cookies.set('name', 'value', { expires: 7 });
// Create an expiring cookie, valid to the path of the current page:
//创建一个即将过期的cookie,对当前页面的路径有效:
Cookies.set('name', 'value', { expires: 7, path: '' });
谢谢观看,如有不足,敬请指教