1. 简介
-
存储内容大小一般支持5MB左右(不同浏览器可能还不一样)
-
浏览器端通过 Window.sessionStorage 和 Window.localStorage 属性来实现本地存储机制。
-
相关API:
-
xxxxxStorage.setItem('key', 'value');
该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。 -
xxxxxStorage.getItem('person');
该方法接受一个键名作为参数,返回键名对应的值。
-
xxxxxStorage.removeItem('key');
该方法接受一个键名作为参数,并把该键名从存储中删除。
-
xxxxxStorage.clear()
该方法会清空存储中的所有数据。
-
-
备注:
- SessionStorage存储的内容会随着浏览器窗口关闭而消失。
- LocalStorage存储的内容,需要手动清除才会消失。
xxxxxStorage.getItem(xxx)
如果xxx对应的value获取不到,那么getItem的返回值是null。JSON.parse(null)
的结果依然是null。
2. demo
<template>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>React App</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<div id="root">
<div class="todo-container">
<div class="todo-wrap">
<MyHeader :addTodoObj="addTodoObj" />
<MyList
:todoList="todoList"
:checkTodo="checkTodo"
:deleteTodoObj="deleteTodoObj"
/>
<MyFooter
:todoList="todoList"
:checkObjAll="checkObjAll"
:clearAllDone="clearAllDone"
/>
</div>
</div>
</div>
</body>
</html>
</template>
<script>
import { watch } from "vue";
import MyFooter from "./components/MyFooter.vue";
import MyHeader from "./components/MyHeader.vue";
import MyList from "./components/MyList.vue";
export default {
name: "App",
components: { MyFooter, MyHeader, MyList },
data() {
return {
todoList: JSON.parse(localStorage.getItem("todoList")) || [],
};
},
methods: {
//添加
addTodoObj(todoObj) {
this.todoList.unshift(todoObj);
},
//勾选or取消勾选
checkTodo(id) {
this.todoList.forEach((todo) => {
if (todo.id === id) todo.done = !todo.done;
});
},
//删除todoObj
deleteTodoObj(id) {
this.todoList = this.todoList.filter((t) => t.id !== id);
},
//勾选全选或者全不选
checkObjAll(done) {
this.todoList.forEach((t) => (t.done = done));
},
//清除所有已完成的任务
clearAllDone() {
this.todoList = this.todoList.filter((t) => t.done !== true);
},
},
watch: {
todoList: {
deep: true,
handler(value) {
localStorage.setItem("todoList", JSON.stringify(value));
},
},
},
};
</script>
<style>
/*base*/
body {
background: #fff;
}
.btn {
display: inline-block;
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
text-align: center;
vertical-align: middle;
cursor: pointer;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
0 1px 2px rgba(0, 0, 0, 0.05);
border-radius: 4px;
}
.btn-danger {
color: #fff;
background-color: #da4f49;
border: 1px solid #bd362f;
}
.btn-danger:hover {
color: #fff;
background-color: #bd362f;
}
.btn:focus {
outline: none;
}
.todo-container {
width: 600px;
margin: 0 auto;
}
.todo-container .todo-wrap {
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
</style>