1.先引用vue文件
<script src="../js/vue.js"></script>
2.写vue的基本样式,用script便签包住
<script>
new Vue ({
el:".box"//el的里值必须跟body的便签值一致
})
</script>
3.body里模板,所有的模板必须写在.box里
<body>
<div class="box">
</div>
</body>
4.编写模板
<div class="box">
<div class="top">
<span>ToDoList</span>
<input type="text" placeholder="添加ToDo" @keyup.enter="addItem">
</div>
<div class="on">
<p>正在进行</p>
<span>{{undolist.length}}</span>
</div>
<div class="content" v-for="item in undolist" :key="item.title">
<input type="checkbox" v-model="item.done">
<span>{{item.title}}</span>
<button @click="delItem(item)">x</button>
</div>
<div class="on">
<p>已经完成</p>
<span>{{donelist.length}}</span>
</div>
<div class="content" v-for="item in donelist" :key="item.title">
<input type="checkbox" v-model="item.done">
<span>{{item.title}}</span>
<button @click="delItem(item)">x</button>
</div>
</div>
5.编写vue
<script>
new Vue({
el: ".box",
data() {
return {
list: JSON.parse(localStorage.getItem("todo") || "[]")
}
},
watch: {
"list": {
handler() {
localStorage.setItem("todo", JSON.stringify(this.list))
}
}
},
methods: {
//添加元素
addItem(e) {
this.list.unshift({ done: false, title: e.target.value })
e.target.value = "";
},
//删除元素
delItem(item) {
var end = this.list.indexOf(item);
this.list.splice(end, 1);
}
},
computed: {
undolist() {
return this.list.filter(item => !item.done);
},
donelist() {
return this.list.filter(item => item.done);
}
}
})
</script>
6.编写样式
<style>
.box {
width: 600px;
height: 400px;
background-color: #ccc;
}
.top {
display: flex;
justify-content: space-between;
align-items: center;
height: 45px;
background-color: #000;
}
.top input {
margin-right: 10px;
border: 0;
outline: none;
border-radius: 5px;
width: 300px;
height: 20px;
text-indent: 1em;
}
.top span {
margin-left: 10px;
color: #fff;
}
p {
font-size: 20px;
font-weight: 900;
margin-left: 10px;
}
.content {
width: 560px;
height: 30px;
margin-left: 10px;
background-color: #fff;
}
.content input {
margin-top: 6px;
margin-left: 10px;
width: 20px;
height: 20px;
background-color: #fff;
}
.content button {
float: right;
margin-top: 6px;
margin-right: 5px;
border: 0;
border-radius: 50%;
color: #f00;
}
.on {
display: flex;
justify-content: space-between;
align-items: center;
}
.on span {
width: 20px;
height: 20px;
text-align: center;
background-color: #fff;
border-radius: 10px;
margin-right: 10px;
}
</style>
效果图