Cookie的使用(js-cookie插件)

65 篇文章 3 订阅
本文介绍了如何使用js-cookie库在前端进行Cookie的设置、读取和删除操作,包括设置过期时间、指定作用域以及存储和解析JSON对象。此外,还展示了封装的auth.js模块,用于获取、设置和移除特定的Token Cookie。
摘要由CSDN通过智能技术生成

一、安装

npm install js-cookie --save

二、引用

import Cookies from 'js-cookie'

三、一般使用

1.存到Cookie去

// Create a cookie, valid across the entire site:  
Cookies.set('name', 'value');  
  
// Create a cookie that expires 7 days from now, valid across the entire site:  
Cookies.set('name', 'value', { expires: 7 });  
 
// Create an expiring cookie, valid to the path of the current page:  
Cookies.set('name', 'value', { expires: 7, path: '' });  

2.在Cookie中取出

// Read cookie:  
Cookies.get('name'); // => 'value'  
Cookies.get('nothing'); // => undefined  
   
// Read all visible cookies:  
Cookies.get(); // => { name: 'value' }  

3.删除

// Delete cookie:  
Cookies.remove('name');  
   
// Delete a cookie valid to the path of the current page:  
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:  
Cookies.set('name', 'value');  
   
// Create a cookie that expires 7 days from now, valid across the entire site:  
Cookies.set('name', 'value', { expires: 7 });  
   
// Create an expiring cookie, valid to the path of the current page:  
Cookies.set('name', 'value', { expires: 7, path: '' });  

如下:自己封装util

auth.js

import Cookies from 'js-cookie'

const TokenKey = 'Admin-Token'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江湖行骗老中医

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值