vue实现简易todolist
实现简易TodoList的步骤
创建Vue项目
使用Vue CLI或Vite快速初始化一个Vue项目。例如通过Vite创建:
npm create vite@latest vue-todolist --template vue
组件结构设计
新建TodoList.vue作为主组件,包含输入框、任务列表和状态展示区域。
数据定义与双向绑定
在<script setup>中定义响应式数据和方法:
<script setup>
import { ref } from 'vue'
const tasks = ref([])
const newTask = ref('')
const addTask = () => {
if (newTask.value.trim()) {
tasks.value.push({ text: newTask.value, completed: false })
newTask.value = ''
}
}
const toggleComplete = (index) => {
tasks.value[index].completed = !tasks.value[index].completed
}
</script>
模板渲染
在<template>中实现交互界面:
<template>
<div class="todo-container">
<input
v-model="newTask"
@keyup.enter="addTask"
placeholder="输入任务内容"
>
<button @click="addTask">添加</button>
<ul>
<li v-for="(task, index) in tasks" :key="index">
<input
type="checkbox"
v-model="task.completed"
@change="toggleComplete(index)"
>
<span :class="{ completed: task.completed }">
{{ task.text }}
</span>
</li>
</ul>
<p>总任务: {{ tasks.length }} | 已完成: {{ completedCount }}</p>
</div>
</template>
计算属性
添加已完成任务的统计功能:
<script setup>
// ...原有代码
import { computed } from 'vue'
const completedCount = computed(() => {
return tasks.value.filter(t => t.completed).length
})
</script>
样式优化
添加基础样式增强视觉效果:
<style scoped>
.completed {
text-decoration: line-through;
color: #888;
}
.todo-container {
max-width: 400px;
margin: 0 auto;
}
ul {
list-style: none;
padding: 0;
}
li {
margin: 8px 0;
display: flex;
align-items: center;
}
</style>
功能扩展建议
- 添加本地存储功能使用
localStorage持久化数据 - 实现任务删除功能
- 增加任务分类过滤(全部/进行中/已完成)
- 添加动画过渡效果
完整组件应包含数据管理、用户交互和状态展示三部分,通过Vue的响应式系统实现数据与视图的自动同步。







