cookie-js操作客户端cookie

在这里插入图片描述

拨云见日
本篇文章主要是介绍在客户端如何操作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: '' });

谢谢观看,如有不足,敬请指教

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值