引入js-cookie.js:
<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和方法
Cookies.set('name', 'value', { expires: 7, path: '' }); //7天過期
Cookies.set('name', { foo: 'bar' }); //設定一個json
複製程式碼
Cookies.get('name'); //獲取cookie
Cookies.get(); //讀取所有的cookie
複製程式碼
Cookies.remove('name'); //刪除cookie時必須是同一個路徑。
複製程式碼
自己寫
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;
}
},
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;
},
getCookie (name) {
let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg)) return unescape(arr[2]);
else return null;
},
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();
},
複製程式碼