一、什么是web存储?
localStorage
- 用于长久保存整个网站的数据,保存的数据没有过期时间,直到手动去除。
sessionStorage
- 用于临时保存同一窗口(或标签页)的数据,在关闭窗口或标签页之后将会删除这些数据。
web存储的数据以 键/值 对存在, web网页的数据只允许该网页访问使用。
存储的数据可以在控制台-Application 中查看,如下图:
二、使用web存储
在使用 web 存储前,应检查浏览器是否支持 localStorage 和sessionStorage:
添加 if 判断 typeof(Storage)!=="undefined"
。
无论是 localStorage,还是 sessionStorage,可使用的API都相同,常用的有如下几个(以localStorage为例):
保存数据:
localStorage.setItem(key,value);
读取数据:localStorage.getItem(key);
删除单个数据:localStorage.removeItem(key);
删除所有数据:localStorage.clear();
得到某个索引的key:localStorage.key(index);
注意:
键/值对通常以字符串存储,你可以按自己的需要转换该格式。
三、 应用示例:toDoList
1、原生js实现:
<body>
<div id="box">
<div id="header">
<span>未完成待办事项:</span>
<input type="text" id="ipt"/>
<button id="btn">添加</button>
</div>
<div>
<h3>未完成事项:</h3>
<div id="wei"></div>
<h3>已完成事项</h3>
<div id="wan"></div>
</div>
</div>
<script>
var addbtn = document.getElementById("btn");
var ipt = document.getElementById("ipt");
var wan = document.getElementById("wan");
var wei = document.getElementById("wei");
var ckbox = document.getElementsByClassName("ck");
var del = document.getElementsByClassName("del");
var arr = [];
//localStorage方法的封装
var storage = {
setItem: function (key, value) {
localStorage.setItem(key, value);
},
getItem: function (key) {
return localStorage.getItem(key);
}
};
//添加按钮的点击事件
addbtn.onclick = function () {
var a = {
name: ipt.value,
isw: false
};
arr.push(a);
//将该数组写入缓存
storage.setItem("todo", JSON.stringify(arr));
bangEle();
};
function bangEle() {
wei.innerHTML = "";
wan.innerHTML = "";
arr.forEach(function (obj, index) {
if (obj.isw) {
wan.innerHTML += "<div><input type='checkbox' checked class='ck' data-index=" + index + ">----" + obj.name + "----<button class='del' data-index=" + index + ">删除</button></div>";
}
else {
wei.innerHTML += "<div><input type='checkbox' class='ck' data-index=" + index + ">----" + obj.name + "----<button class='del' data-index=" + index + ">删除</button></div>";
}
});
addEvent();
}
//checkbox和删除按钮的点击事件
function addEvent() {
for (var i = 0; i < ckbox.length; i++) {
ckbox[i].onclick = function () {
if (this.checked) {
arr[this.getAttribute("data-index")].isw = true;
}
else {
arr[this.getAttribute("data-index")].isw = false;
}
//数组发生变化,更新缓存
storage.setItem("todo", JSON.stringify(arr));
bangEle();
};
del[i].onclick = function () {
arr.splice(this.getAttribute("data-index"), 1);
//数组发生变化,更新缓存
storage.setItem("todo", JSON.stringify(arr));
bangEle();
}
}
};
window.onload = function () {
storage.getItem("todo");
if (JSON.parse(storage.getItem("todo"))) {
arr = JSON.parse(storage.getItem("todo"));
bangEle();
}
};
</script>
</body>
2、vue实现
html:
<template>
<div id="todoList">
<div class="title">
<div class="name">添加事宜:</div>
<div class="ipt">
<input @keypress.enter="enterAdd" type="text" v-model="add" />
<button @click="addList">添加</button>
</div>
</div>
<div clss="s_data">
<p>正在进行的事项:</p>
<ul class="menu" v-bind:title="num=1">
<template v-for="(item,index) in list">
<li v-if="!item.ishas" :key="index">
<input type="checkbox" :checked="item.ishas" @click="changeStatus(index)" />
<span>{{num++}}</span>---
<a href="#">{{item.name}}</a>
<button @click="removeData(index)">刪除</button>
</li>
</template>
</ul>
<p>已经完成的事项:</p>
<ul class="menu" v-bind:title="numw=1">
<template v-for="(item,index) in list">
<li v-if="item.ishas" :key="index">
<input type="checkbox" :checked="item.ishas" @click="changeStatus(index)" />
<span>{{numw++}}</span>---
<a href="#">{{item.name}}</a>
<button>刪除</button>
</li>
</template>
</ul>
</div>
</div>
</template>
js:
<script>
//引入base64 加密解密模块
let Base64=require("js-base64").Base64;
export default {
name: "todoList",
mounted() {
//当前组件挂载完成之后
let data = localStorage.getItem("todo");
if (data) {
this.list = JSON.parse(Base64.decode(data));
}
console.log(this.list);
},
data() {
return {
list: [],
add: "",
};
},
methods: {
enterAdd() {
this.addList();
},
addList() {
if (!this.checkhas()) {
this.list.push({
name: this.add,
ishas: false,
});
}
//添加到緩存
localStorage.setItem("todo", Base64.encode(JSON.stringify(this.list)));
this.add = "";
},
checkhas() {
//检测是否存在
return this.list.some((val, index) => {
return val.name == this.add;
});
},
changeStatus(index) {
this.list[index].ishas = !this.list[index].ishas;
//添加到緩存
localStorage.setItem("todo", Base64.encode(JSON.stringify(this.list)));
},
removeData(index) {
this.list.splice(index, 1);
//添加到緩存
localStorage.setItem("todo", Base64.encode(JSON.stringify(this.list)));
},
},
};
</script>
css(使用的是less):
<style lang="less">
@width: 1180px;
@height: 50px;
.border(@w:1px,@st:solid,@co:#000000) {
border: @w @st @co;
}
#todoList {
margin: 0 auto;
width: @width;
min-height: @height;
display: flex;
flex-direction: column;
.title {
flex: 1;
padding: 10px;
display: flex;
flex-direction: row;
border-bottom: 1px solid #000;
.name {
flex: 1;
font-size: 25px;
font-weight: 700;
}
.ipt {
flex: 5;
display: flex;
align-items: center;
input {
width: @width / 5;
height: 30px;
outline: none;
padding-left: 10px;
box-sizing: border-box;
}
button {
width: @width / 10;
height: 30px;
margin-left: 10px;
}
}
}
.s_data {
padding: 10px;
}
.menu {
list-style: none;
li {
list-style: none;
a {
text-decoration: none;
color: #000;
}
}
}
}
</style>