此案例较为简单,功能需求也比较单一,后续会使用node.js+mysql来进行更加复杂的需求开发的。
主要分为5部分
1、列表渲染
设置好一个数组,使用v-for数组遍历即可
<template>
<!-- 主体区域 -->
<section id="app" style="width: 600px; margin: 180px auto">
<!-- 输入框 -->
<header class="header">
<h1>todo记事本</h1>
<input
v-model="todoName"
@keyup.enter="add"
placeholder="请输入todo任务"
class="new-todo"
/>
<button @click="add" class="add">添加 todo</button>
</header>
<!-- 列表区域 -->
<section class="main">
<ul class="todo-list">
<li class="todo" v-for="(item, index) in todoList" :key="item.id">
<div class="view">
<span class="index">{ { index + 1 }}.</span>
<label>{ { item.name }}</label>
<button @click="del(item.id)" class="destroy"></button>
</div>
</li>
</ul>
</section>
<!-- 统计和清空 → 如果没有任务了,底部隐藏掉 → v-show -->
<footer class="footer" v-show="todoList.length > 0">
<!-- 统计 -->
<span class="todo-count"
>合 计:<strong> { { todoList.length }} </strong></span
>
<!-- 清空 -->
<button @click="clear" class="clear-completed">清空任务</button>
</footer>
</section>
</template>
<script>
export default {
name: "ToDoList",
data() {
return {
todoName: "",
todoList: [
{ id: 1, name: "吃饭" },
{ id: 2, name: "打豆" },
{ id: 3, name: "摸鱼" },
],
};
},
};
</script>
2、删除功能
<script>
export default {
name: "ToDoList",
data() {
return {
todoName: "",
todoList: [
{ id: 1, name: "吃饭" },
{ id: 2, name: "打豆" },
{ id: 3, name: "摸鱼" },
],
};
},
methods: {
del(id) {
// console.log(id) => filter 保留所有不等于该 id 的项
this.todoList= this.todoList.filter((item) => item.id !== id);
},
},
};
</script>
3、添加功能
<script>
export default {
name: "ToDoList",
data() {
return {
todoName: "",
todoList: [
{ id: 1, name: "吃饭" },
{ id: 2, name: "打豆" },
{ id: 3, name: "摸鱼" },
],
};
},
methods: {
del(id) {
// console.log(id) => filter 保留所有不等于该 id 的项
this.todoList= this.todoList.filter((item) => item.id !== id);
},
add() {
if (this.todoName.trim() === "") {
alert("请输入任务名称");
return;
}
this.todoList.unshift({
id: +new Date(),
name: this.todoName,
});
this.todoName = "";
},
},
};
</script>
4、底部统计和清空
底部统计其实就是todoList数组的长度,清空的话直接将todoList数组赋值为空即可
<script>
export default {
name: "ToDoList",
data() {
return {
todoName: "",
todoList: [
{ id: 1, name: "吃饭" },
{ id: 2, name: "打豆" },
{ id: 3, name: "摸鱼" },
],
};
},
methods: {
del(id) {
// console.log(id) => filter 保留所有不等于该 id 的项
this.todoList= this.todoList.filter((item) => item.id !== id);
},
add() {
if (this.todoName.trim() === "") {
alert("请输入任务名称");
return;
}
this.todoList.unshift({
id: +new Date(),
name: this.todoName,
});
this.todoName = "";
},
clear() {
this.todoList= [];
},
},
};
</script>
5、效果展示