2. 获取cookie里面的token:
2.1 我们在用vue.js里面的index.html写一个全局的函数:
3. 这样我们通过传入cookie的key名就可以获取到后面的token了,如:
本地存储对比:sessionStorage,关闭窗口就被清除;
localStorage,一直存在直到手动删除;
cookie,设置有效期,可以直接实现标题的需求
今天不想多说话,直接贴上代码:
//判断是否支持 比如浏览器开启了隐私模式var isCookie = () = >{ return navigator.cookieEnabled}//存储function setCookie(cname, cvalue, exdays = 0) { cvalue = encodeURIComponent(JSON.stringify(cvalue)) if (exdays >0) {var d = new Date().getTime() + exdays * 24 * 3600 * 1000 + 8 * 3600 * 1000 var expires = "expires=" + new Date(d).toUTCString() document.cookie = cname + "=" + cvalue + "" + expires + "path=/" } else {document.cookie = cname + "=" + cvalue + "" + "path=/" }}//获取function getCookie(cname) { var name = cname + "=" var ca = document.cookie.split("") for (var i = 0i <ca.lengthi++) {var c = ca[i] while (c.charAt(0) == " ") { c = c.substring(1) }if (c.indexOf(name) == 0) { let d = c.substring(name.length, c.length) return JSON.parse(decodeURIComponent(d)) } } return ""}//获取 通过正则// function getCookie(name) {// var arr,// reg = new RegExp("(^| )" + name + "=([^]*)(|$)")// if ((arr = document.cookie.match(reg))) {// return JSON.parse(decodeURIComponent(arr[2]))// } else {// return null// }// }//删除function deleteCookie(name) { var date = new Date() date.setTime(date.getTime() - 1) var delValue = getCookie(name) if (delValue) {document.cookie = name + "=" + delValue + "expires=" + date.toGMTString() }}
使用示例:
//定义keyconst tk = "tk2020"const uk = "uk2020"//保存setCookie(tk, "14332239527007001", 0)setCookie(uk, { id: 1, name: "以气御码" }, 0)//获取let token = getCookie(tk)let user = getCookie(uk)console.log(token)console.log(user)
当使用setCookie时,传0或不传,表示关闭浏览器后就被清除,截图预览:
当登录的信息存储为这种形式,可以实现关闭浏览器,就清除登录信息。也可以再配合登录有效期,总不能“只要不关浏览器,就不退出登录了”。
文档:
MDN Cookie(https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie)W3c Cookie(https://www.w3school.com.cn/js/js_cookies.asp)菜鸟教程 Cookie(https://www.runoob.com/js/js-cookies.html)