用localStorage实现TodoList效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>demo3</title>
<link rel="stylesheet" href="css/bootstrap.css">
<script src="./js/vue.js"></script>
<style>
.box {
margin: 0 auto;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
width: 320px;
background-color: #fff;
color: #303133;
}
.btn-group {
margin-top: 10px;
margin-bottom: 10px;
}
.bor {
padding: 5px;
border: 0;
border-radius: 0 !important;
border-bottom: 1px solid #ddd !important;
display: flex;
justify-content: space-between;
align-items: center;
}
.bor>p {
flex: 1;
display: flex;
align-items: center;
margin: 0;
cursor: pointer;
}
.ss {
text-decoration: line-through;
}
.select {
background-color: cornflowerblue !important;
}
.bors {
border: 0;
}
</style>
</head>
<body>
<div id="app">
<div class="container">
<h3 class="text-center font"><strong>ToDoList</strong></h3>
<ul class="box list-group">
<li class="list-group-item">
<div class="input-group">
<input type="text" class="form-control" placeholder="请输入内容" v-model="val">
<span class="input-group-btn">
<button class="btn btn-default" type="button" @click="add">添加</button>
</span>
</div>
</li>
<li class="list-group-item text-center">
<div class="btn-group">
<button @click="activeIndex=0" type="button" class="btn btn-default"
:class="activeIndex==0?'select':''">全部 </button>
<button @click="activeIndex=1" type="button" class="btn btn-default"
:class="activeIndex==1?'select':''">未完成 </button>
<button @click="activeIndex=2" type="button" class="btn btn-default"
:class="activeIndex==2?'select':''">完成 </button>
</div>
<ul class="list-group text-left">
<li class="bor" v-for="item in showList" :key="item.id">
<p :class="item.finished?'ss':''" @click="item.finished=!item.finished">{{item.val}}</p>
<button class="btn btn-primary" @click="deleteFn(item.id)">删除</button>
</li>
</ul>
</li>
</ul>
</div>
</div>
</body>
<script>
let vm = new Vue({
el: "#app",
data: {
activeIndex: 0,
list: JSON.parse(localStorage.getItem('list')) || [],
val: '',
showList: JSON.parse(localStorage.getItem('list')) || []
},
methods: {
add() {
let obj = {
id: new Date().getTime(),
val: this.val,
finished: false
};
this.list.push(obj);
},
deleteFn(id) {
this.list = this.list.filter(item => item.id != id);
}
},
watch: {
activeIndex(value) {
if (value == 0) {
this.showList = this.list;
} else if (value == 1) {
this.showList = this.list.filter(item => !item.finished)
} else if (value == 2) {
this.showList = this.list.filter(item => item.finished)
}
},
list: {
deep: true,
handler(value) {
console.log(234234);
if (this.activeIndex == 0) {
this.showList = value;
} else if (this.activeIndex == 1) {
this.showList = value.filter(item => !item.finished)
} else if (this.activeIndex == 2) {
this.showList = value.filter(item => item.finished)
}
localStorage.setItem('list', JSON.stringify(value))
}
}
}
})
</script>
</html>