模板地址:vue官网上的示例
1 输入框输入,回车添加todo信息
2 每条todo信息后增加删除按钮
3 每条todo信息增加complete状态,列表前增加checkbox,选中后修改complete值,根据complete值修改todo信息样式
4 编辑:双击todo信息隐藏checkout、info、button,显示输入框,回车或失去焦点完成编辑,esc退出编辑
5 提示剩余未完成todo数量,清除已完成todo
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<style>
.completed {
text-decoration: line-through;
color: darkgrey;
}
</style>
</head>
<body>
<div id="root">
<!-- 输入框 -->
<input v-model="newTodo" @keyup.enter="addTodo" />
<!-- todo列表 -->
<ul>
<li v-for="(todo, index) in todoList" :class="{completed: todo.completed}">
<div v-show="editTodoIndex != index">
<!-- 状态勾选 -->
<input type="checkbox" v-model="todo.completed" />
<!-- todo信息 -->
<label @dblClick="editTodo(todo, index)">{
{todo.info}}</label>
<!-- 删除按钮 -->
<button @click="removeTodo(index)">删除</button>
</div>
<!-- 编辑框 -->
<input v-show="editTodoIndex == index" v-model="todo.info" @blur="doneEdit(todo, index)"
@keyup.enter="doneEdit(todo, index)" @keyup.esc="cancelEdit(todo, index)"/>
</li>
</ul>
<footer v-show="todoList.length">
<!-- 未完成todo数 -->
<a>剩下{
{remainCount}}</a>
<!-- 清除已完成todo -->
<button v-show="todoList.length > remainCount" @click="clearComplete">清除已完成</button>
</footer>
</div>
<script>
var app = new Vue({
el: "#root",
data: {
newTodo: "", // 新增输入框的内容
todoList: [], // 保存所有todo信息,数组元素:{completed: 完成true/未完成false,info:todo信息string}
editTodoIndex: -1, // 正在编辑的todo信息的index,没有todo信息正在编辑即为-1
beforeEditCache: "" // 暂存编辑之前的todo信息,退出编辑后需要赋值回去
},
methods: {
// 回车添加事件
addTodo: function () {
if (this.newTodo) {
this.todoList.push({
info: this.newTodo, completed: false })
}
this.newTodo = '';
},
// 删除事件
removeTodo: function (index) {
this.todoList.splice(index, 1)
},
// 开始编辑,保存编辑之前的todo信息,todo信息的index
editTodo: function (todo, index) {
this.beforeEditCache = todo.info; // 不要保存整个todo,因为编辑的时候直接改变todo.info,beforeEditCache也会改变
this.editTodoIndex = index;
},
// 完成编辑,将editTodoIndex恢复初始值,如果输入框为空,则删除当前todo
doneEdit: function (todo, index) {
this.editTodoIndex = -1;
if (!todo.info) {
this.removeTodo(index);
}
},
// 退出编辑,将提前保存的todo信息赋值回去
cancelEdit: function (todo, index) {
todo.info = this.beforeEditCache;
this.editTodoIndex = -1;
},
// 清除已完成
clearComplete: function () {
this.todoList = this.todoList.filter(todo => !todo.completed)
}
},
computed: {
// 实时计算剩余未完成todo数
remainCount: function() {
return this.todoList.filter(todo => !todo.completed).length;
}
}
})
</script>
</body>
</html>