学了这么多知识点,总得找个项目练手。我选了经典的 TodoList 待办事项,别看它简单,五脏俱全,能覆盖很多基础知识点。
我用 Vue + 原生 CSS 来做。功能包括:添加待办、删除待办、切换完成状态、筛选全部 / 已完成 / 未完成、统计未完成数量、本地存储持久化。
核心代码片段:
html
预览
<button @click="filter = 'all'">全部
<button @click="filter = 'active'">未完成
<button @click="filter = 'done'">已完成
未完成:{{ activeCount }}
javascript
运行
const app = new Vue({
el: '#app',
data: {
inputValue: '',
filter: 'all',
list: JSON.parse(localStorage.getItem('todos') || '[]')
},
computed: {
filterList() {
if (this.filter === 'active') return this.list.filter(item => !item.done);
if (this.filter === 'done') return this.list.filter(item => item.done);
return this.list;
},
activeCount() {
return this.list.filter(item => !item.done).length;
}
},
methods: {
addTodo() {
if (!this.inputValue.trim()) return;
this.list.push({
id: Date.now(),
text: this.inputValue,
done: false
});
this.inputValue = '';
},
deleteTodo(id) {
this.list = this.list.filter(item => item.id !== id);
}
},
watch: {
list: {
deep: true,
handler(val) {
localStorage.setItem('todos', JSON.stringify(val));
}
}
}
});
做的过程中还是踩了不少坑。比如 v-for 循环的 key 值一开始随便写了索引,后来了解到 key 的重要性,改成了每个事项的唯一 id。还有本地存储 localStorage,最开始直接存对象,取出来变成了 [object Object],才想起要转成 JSON 字符串存取。
做完之后部署到了 Gitee Pages 上,手机也能访问。虽然是个小项目,但从设计到实现全是自己一个人完成的,成就感满满。更重要的是,通过实战把之前零散的知识点串了起来,发现了很多自己掌握不牢的地方。