在我们的日常工作和生活中,待办事项列表是一种常用的工具,可以帮助我们管理任务,提高效率。本文将介绍如何使用 Vue 框架构建一个简单的待办事项列表,以便于用户管理他们的任务。
该待办事项列表具有以下基本功能:
首先,我们需要初始化一个数据数组来存储任务列表。可以使用 Vue 的 ref
函数来创建一个可变的响应式数组。
import { ref } from 'vue'
const tasks = ref([
{
id: 1,
title: 'Buy a pack of coffee',
time: '08:00 - 09:00',
completed: false
},
// ... 其他任务
])
接下来,我们需要创建模板来显示任务列表。模板使用 Vue 的 JSX 语法,并使用 v-for
指令遍历任务数组。
<template>
<div class="flex flex-col h-screen bg-gray-100">
<div class="flex items-center justify-between h-16 bg-white shadow">
<div class="text-xl font-bold text-gray-900">Today</div>
<div>
<button class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md shadow">
Add New
</button>
</div>
</div>
<div class="flex-1 overflow-y-auto">
<div class="max-w-md mx-auto px-4 py-4">
<div class="flex items-center justify-between mb-4">
<div class="text-lg font-medium text-gray-900">5</div>
<div class="text-sm text-gray-500">Tasks today</div>
</div>
<div class="bg-white shadow rounded-md p-4">
<!-- 任务列表 -->
<div v-for="task in tasks" :key="task.id" class="task-item">
<input type="checkbox" @click="toggleTask(task.id)" />
<label>{{ task.title }}</label>
<time>{{ task.time }}</time>
</div>
</div>
</div>
</div>
</div>
</template>
当用户点击 "Add New" 按钮时,我们需要添加一个新任务到列表中。可以使用 Vue 的 push
方法来向数组中添加元素。
<script lang="tsx" setup>
// ... 其他代码
const addNewTask = () => {
tasks.value.push({
id: Date.now(),
title: 'New Task',
time: '00:00 - 00:00',
completed: false
})
}
</script>
当用户点击任务旁边的复选框时,我们需要将该任务标记为已完成。可以使用 Vue 的 v-model
指令来绑定复选框的状态到任务的 completed
属性。
<input type="checkbox" v-model="task.completed" />
当用户想要从列表中删除一个任务时,可以使用 Vue 的 splice
方法来从数组中删除元素。
const removeTask = (id) => {
const index = tasks.value.findIndex((task) => task.id === id)
if (index !== -1) {
tasks.value.splice(index, 1)
}
}
通过本文介绍的步骤,我们构建了一个功能齐全的待办事项列表。在这个过程中,我们学习了如何使用 Vue 的响应式数据、JSX 模板、事件处理和数组操作等功能。
未来,我们可以对该卡片功能进行以下拓展和优化: