新建项目(不知道怎么新建项目?参考文章:vue-cli3 搭建vue项目)
目录结构
界面显示
添加store.js
export default {
fetch: (key) => JSON.parse(window.localStorage.getItem(key)),
save: (data, key) => window.localStorage.setItem(key, JSON.stringify(data)),
};
将两个操作localStorage的函数export出去。
需要在使用的时候import进来。
App.vue代码编写
html
<template>
<div id="app">
<div class="wrap">
<input type="text" v-model="keyword" @keydown.enter="addData" />
<ul v-if="list.length">
<li
v-for="(item, index) in list"
:key="index"
@click="changeState(index)"
:class="{complete: item.state}"
>{{ item.txt }}</li>
</ul>
</div>
</div>
</template>
script
import store from "./common/store"; // 引入store模块
const STORAGE_KEY = "my-key";
export default {
name: "app",
data() {
return {
keyword: "",
list: store.fetch(STORAGE_KEY) ? store.fetch(STORAGE_KEY) : [], //从本地存储中获取数据
};
},
components: {},
mounted() {},
methods: {
// 添加数据
addData() {
this.list.push({
txt: this.keyword,
state: false,
});
this.keyword = "";
},
// 点击后改变状态
changeState(index) {
this.list[index].state = !this.list[index].state;
},
},
watch: {
// 这里监听整个list数据的变化,避免每次修改数据的时候都需要进行本地存储
list: {
handler() {
store.save(this.list, STORAGE_KEY); //写入本地存储
},
deep: true, // 切换为false之后,点击切换状态,刷新看效果,未触发watch。
},
},
};
style
*{margin: 0;padding: 0;}
.wrap {width: 80%;margin: 0 auto;}
input {height: 30px;width: 100%;}
li {
height: 30px;
line-height: 30px;
background: #e2e2e2;
margin: 4px 0;
cursor: pointer;
list-style-type: none;
padding: 0 10px;
}
li.complete {background: #5cce5c;color: #fff;}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。