1、首先,理解什么是cookies?
cookies:存储在客户端,数据量小的,会过期的数据,以字符串形式存储
cookie操作代码示例:
<script>
window.onload = function() {
function setCookie(name, value, time) {
var oDate = new Date();
oDate.setDate(oDate.getDate() + time);
document.cookie = `${name}=${value};path=/;expires=${oDate}`;
}
function getCookie(name) {
var str = document.cookie;
var arr = str.split(';');
for (let i = 0; i < arr.length; i++) {
var arr2 = arr[i].split('=');
if (arr2[0] == name) {
return arr2[1];
}
}
return '';
}
// function removeCookie(name) {
// setCookie(name, '', -1);
// }
setCookie('username', 'zxq', 2);
setCookie('SameSite', 'Lax', 2);
removeCookie('SameSite', '', -1);
console.log(getCookie('username')) //'zxq'
}
</script>
2、localStorage及sessionStorage
session:以键值对形式存储在服务端的数据
localStorage及sessionStorage:以键值对形式存储在客户端的数据
操作示例:
<script>
window.onload = function() {
sessionStorage.setItem('use', 'zxq');
console.log(sessionStorage.getItem('use')); //'zxq'
// sessionStorage.removeItem('use');
// //sessionStorage.clear();//全部清除
localStorage.setItem('username', 'zxq');
console.log(localStorage.getItem('username')); //'zxq'
// localStorage.removeItem('username');
// localStorage.clear();
}
</script>
3、cookie和localStorage及sessionStorage的区别
- cookie会过期,数据小,每次url请求会携带cookies信息,同源窗口访问
- localStorage数据比cookies大,客户端持久化存储,url请求不携带,同源窗口访问
- sessionStorage与localStorage相似,但是有效时间为一个会话期间,只能由当前浏览器的窗口共享数据
4、实战,用sessionStorage模拟一个首页验证登陆的功能
部分代码:
if(this.loginForm.username != sessionStorage.getItem('username')){
alert('用户名填写错误!')
}else if(this.loginForm.password != sessionStorage.getItem('password')){
alert('用户密码填写错误!')
}else{
this.$router.push({path:'/',query:{username:this.loginForm.username}})
}
github地址:[https://github.com/Zxq-zn/vuemanager/tree/master/src/components/login]