js-cookie.js的使用
作者:互联网
js-cookie.js的使用
3种引入js-cookie.js的方法:
一. 直接引用cdn:
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
二. 本地下载下来:
<script src="./js/js.cookie.js"></script>
三. 模块化开发时:
import Cookies from 'js-cookie'
js-cookie.js常用的API和方法
-
设置cookie
Cookies.set('name', 'value', { expires: 7, path: '' }); //7天过期
Cookies.set('name', { foo: 'bar' }); //设置一个json -
读取cookie
Cookies.get('name'); //获取cookie
Cookies.get(); //读取所有的cookie -
删除cookie
Cookies.remove('name'); //删除cookie时必须是同一个路径。
不想引入?那就自己写一个
封装三个方法: 设置:setCookie
,获取:getCookie
,删除;delCookie
//Get time
getsec (str) {
let str1 = str.substring(1, str.length) * 1;
let str2 = str.substring(0, 1);
if (str2 == "s") {
return str1 * 1000;
} else if (str2 == "h") {
return str1 * 60 * 60 * 1000;
} else if (str2 == "d") {
return str1 * 24 * 60 * 60 * 1000;
}
},
// Set the cookie
setCookie (name, value, time, path, domain) {
let strsec = this.getsec(time);
let exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=" + path + ";domain=" + domain;
},
// Read cookies
getCookie (name) {
let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg)) return unescape(arr[2]);
else return null;
},
// Remove cookies
delCookie () {
let exp = new Date();
exp.setTime(exp.getTime() - 1);
let cval = this.getCookie(name);
if (cval !== null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
},
标签:Cookies,name,js,let,exp,使用,cookie 来源: https://www.cnblogs.com/xwj1717/p/16641963.html