<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>待办事项</title>
</head>
<body>
<div id="app">
<!-- 标题 -->
<div class="header">
<h2 class="title">待办事项</h2>
<h3 class="subtitle">ToDoList...</h3>
</div>
<!-- 输入新待办事项 -->
<div class="input">
<input
class="input-todo"
type="text"
placeholder="请输入新待办事项"
v-model.trim="inputValue"
ref="inputRef"
@keydown.enter="handleAdd"
/>
<button v-on:click="handleAdd">添加</button>
</div>
<!-- 显示所有待办事项列表 -->
<ul class="list" v-if="total() > 0">
<li class="list-item" v-for="(todo, index) of todos">
<input type="checkbox" v-model="todo.completed">
{{ index }} - {{ todo.id }} - {{ todo.title }} - {{ todo.completed ? '已' : '未' }}完成 -
<button @click="handleModify(todo)">修改</button>
<button @click="handleRemove(todo.id)">删除</button>
</li>
</ul>
<div v-else>待办事项为空,请添加新待办事项!</div>
<!-- 统计 -->
<div>
共有{{ total() }}项待办事项,
已完成{{ completedCount }}项,
未完成{{ uncompletedCount }}项
</div>
</div>
<script src="./libs/vue/vue.js"></script>
<script>
// 初始化一个待办事项数组
const _todos = Array(6).fill(null).map((_, index) => ({
id: index + 1,
title: '待办事项' + (index + 1),
completed: Math.random() > 0.5,
}))
// id 的编号
let index = _todos.length
// 创建 Vue 实例
const vm = new Vue({
el: '#app',
data: {
todos: _todos, // 所有待办事项
inputValue: '', // 输入框中双向绑定的数据
},
computed: { // 计算属性
// completedCount() { // 已完成数量
// return this.todos.reduce((result, todo) => todo.completed ? result + 1 : result, 0)
// },
completedCount: { // 已完成数量
get() {
return this.todos.reduce((result, todo) => todo.completed ? result + 1 : result, 0)
},
},
uncompletedCount() { // 未完成数量
return this.todos.reduce((result, todo) => !todo.completed ? result + 1 : result, 0)
}
},
methods: {
// 所有待办事项数量
total() {
return this.todos.length
},
// 处理添加新待办事项
handleAdd() {
// 让文本框获得焦点
this.$refs.inputRef.focus()
// document.querySelector('.input-todo').focus()
// 判断是否有输入内容
if (this.inputValue.length === 0) {
return
}
// 将文本框中输入的待办事项内容添加到所有待办事项的数组中
this.todos.push({
id: ++index,
title: this.inputValue,
completed: false,
})
// 清空文本框
this.inputValue = ''
},
// 修改待办事项状态
handleModify(todo) {
todo.completed = !todo.completed
},
// 删除待办事项状态
handleRemove(id) {
this.todos = this.todos.filter(todo => todo.id !== id)
},
}
})
</script>
</body>
</html>