Vue TodoList

以下是基于 Vue 3 组合式 API (Composition API) 的TodoList 应用。首先构建静态结构,然后定义响应式数据。

html 复制代码
<!DOCTYPE html><html lang="zh-CN"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue3 TodoList 实战</title>
    <!-- 引入 TailwindCSS 用于快速样式 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Vue 3 -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <!-- 引入 Font Awesome 图标 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .todo-item-enter-active,
        .todo-item-leave-active {
            transition: all 0.3s ease;
        }
        .todo-item-enter-from,
        .todo-item-leave-to {
            opacity: 0;
            transform: translateY(20px);
        }
        .custom-checkbox:checked + div {
            background-color: #10B981;
            border-color: #10B981;
        }
        .custom-checkbox:checked + div svg {
            display: block;
        }
        /* 自定义滚动条 */
        ::-webkit-scrollbar {
            width: 6px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f1f1; 
        }
        ::-webkit-scrollbar-thumb {
            background: #888; 
            border-radius: 3px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #555; 
        }
    </style></head><body>
    <div id="app" class="flex items-center justify-center p-4">
        <div class="bg-white w-full max-w-md rounded-xl shadow-2xl overflow-hidden flex flex-col h-[80vh]">
            
            <!-- 头部区域:标题与输入框 -->
            <header class="bg-indigo-600 p-6 text-white shrink-0">
                <h1 class="text-2xl font-bold mb-4 flex items-center gap-2">
                    <i class="fa-solid fa-list-check"></i> 待办清单
                </h1>
                <div class="relative">
                    <input 
                        type="text" 
                        v-model.trim="newTodoTitle"
                        @keyup.enter="addTodo"
                        placeholder="添加新任务..." 
                        class="w-full py-3 px-4 pr-12 rounded-lg text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-300 shadow-inner transition-all"
                    >
                    <button 
                        @click="addTodo"
                        class="absolute right-2 top-1/2 transform -translate-y-1/2 bg-indigo-500 hover:bg-indigo-700 text-white p-2 rounded-md transition-colors"
                    >
                        <i class="fa-solid fa-plus"></i>
                    </button>
                </div>
            </header>

            <!-- 主体区域:任务列表 -->
            <main class="flex-1 overflow-y-auto p-4 bg-gray-50 relative">
                <!-- 空状态提示 -->
                <div v-if="todos.length === 0" class="flex flex-col items-center justify-center h-full text-gray-400">
                    <i class="fa-regular fa-clipboard text-6xl mb-4 opacity-50"></i>
                    <p>暂无待办事项,快去添加吧!</p>
                </div>

                <!-- 任务列表 -->
                <transition-group name="todo-item" tag="ul" class="space-y-3">
                    <li 
                        v-for="todo in filteredTodos" 
                        :key="todo.id"
                        class="bg-white p-4 rounded-lg shadow-sm border border-gray-100 flex items-center justify-between group hover:shadow-md transition-shadow"
                    >
                        <div class="flex items-center gap-3 flex-1">
                            <!-- 自定义复选框 -->
                            <label class="relative flex items-center cursor-pointer">
                                <input 
                                    type="checkbox" 
                                    class="custom-checkbox sr-only" 
                                    :checked="todo.completed"
                                    @change="toggleTodo(todo)"
                                >
                                <div class="w-6 h-6 border-2 border-gray-300 rounded-full flex items-center justify-center transition-colors">
                                    <svg class="w-4 h-4 text-white hidden pointer-events-none" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                                </div>
                            </label>
                            
                            <!-- 任务文本 -->
                            <span 
                                class="text-gray-700 transition-all duration-300 select-none cursor-pointer"
                                :class="{ 'line-through text-gray-400': todo.completed }"
                                @click="toggleTodo(todo)"
                            >
                                {{ todo.title }}
                            </span>
                        </div>

                        <!-- 删除按钮 -->
                        <button 
                            @click="removeTodo(todo.id)"
                            class="text-gray-400 hover:text-red-500 p-2 rounded-full hover:bg-red-50 transition-all opacity-0 group-hover:opacity-100 focus:opacity-100"
                            title="删除任务"
                        >
                            <i class="fa-solid fa-trash-can"></i>
                        </button>
                    </li>
                </transition-group>
            </main>

            <!-- 底部区域:统计与筛选 -->
            <footer class="bg-white border-t border-gray-200 p-4 shrink-0">
                <div class="flex flex-col sm:flex-row justify-between items-center gap-4 text-sm text-gray-600">
                    
                    <!-- 剩余数量 -->
                    <span class="font-medium">
                        <span class="text-indigo-600 font-bold">{{ remainingCount }}</span> 项未完成
                    </span>

                    <!-- 筛选按钮 -->
                    <div class="flex bg-gray-100 rounded-lg p-1">
                        <button 
                            v-for="filter in filters" 
                            :key="filter.value"
                            @click="currentFilter = filter.value"
                            class="px-4 py-1.5 rounded-md transition-all duration-200"
                            :class="currentFilter === filter.value ? 'bg-white text-indigo-600 shadow-sm font-semibold' : 'text-gray-500 hover:text-gray-700'"
                        >
                            {{ filter.label }}
                        </button>
                    </div>

                    <!-- 清除已完成 -->
                    <button 
                        v-if="completedCount > 0"
                        @click="clearCompleted"
                        class="text-gray-500 hover:text-red-500 transition-colors flex items-center gap-1"
                    >
                        <i class="fa-solid fa-broom"></i> 清除已完成
                    </button>
                </div>
            </footer>
        </div>
    </div>

    <script>
        const { createApp, ref, computed, watch, onMounted } = Vue;

        createApp({
            setup() {
                // 1.2 展示动态数据:定义数据类型和名称
                // 数据保存在根组件中,通过 props/events 或 provide/inject 分发(此处为简化演示放在根组件)
                const newTodoTitle = ref('');
                const todos = ref([]);
                const currentFilter = ref('all'); // 'all', 'active', 'completed'

                const filters = [
                    { label: '全部', value: 'all' },
                    { label: '未完成', value: 'active' },
                    { label: '已完成', value: 'completed' }
                ];

                // 计算属性
                const remainingCount = computed(() => {
                    return todos.value.filter(t => !t.completed).length;
                });

                const completedCount = computed(() => {
                    return todos.value.filter(t => t.completed).length;
                });

                const filteredTodos = computed(() => {
                    switch (currentFilter.value) {
                        case 'active':
                            return todos.value.filter(t => !t.completed);
                        case 'completed':
                            return todos.value.filter(t => t.completed);
                        default:
                            return todos.value;
                    }
                });

                // 1.3 交互:从绑定事件监听开始
                const addTodo = () => {
                    if (!newTodoTitle.value) return;
                    
                    const newTodo = {
                        id: Date.now(),
                        title: newTodoTitle.value,
                        completed: false
                    };
                    
                    todos.value.unshift(newTodo); // 添加到开头
                    newTodoTitle.value = ''; // 清空输入框
                };

                const toggleTodo = (todo) => {
                    todo.completed = !todo.completed;
                };

                const removeTodo = (id) => {
                    todos.value = todos.value.filter(t => t.id !== id);
                };

                const clearCompleted = () => {
                    todos.value = todos.value.filter(t => !t.completed);
                };

                // 数据持久化:LocalStorage
                // 监听 todos 变化,自动保存
                watch(todos, (newVal) => {
                    localStorage.setItem('vue-todos', JSON.stringify(newVal));
                }, { deep: true });

                // 初始化时加载数据
                onMounted(() => {
                    const savedTodos = localStorage.getItem('vue-todos');
                    if (savedTodos) {
                        try {
                            todos.value = JSON.parse(savedTodos);
                        } catch (e) {
                            console.error('Failed to parse todos', e);
                        }
                    }
                });

                return {
                    newTodoTitle,
                    todos,
                    currentFilter,
                    filters,
                    remainingCount,
                    completedCount,
                    filteredTodos,
                    addTodo,
                    toggleTodo,
                    removeTodo,
                    clearCompleted
                };
            }
        }).mount('#app');
    </script></body></html>
相关推荐
多加点辣也没关系9 小时前
JavaScript|第41章:性能优化实战
开发语言·javascript·性能优化
feixing_fx11 小时前
解构与展开:可读性和性能的取舍
开发语言·前端·javascript·前端框架
前端架构师-老李13 小时前
html教程:header、nav、main、footer 四个标签各管哪一块?
前端·html
烟雨空灵13 小时前
25 天做了个独立开发者作品橱窗,收录 340+ 件作品,代码全开源
前端·node.js
wangruofeng14 小时前
怎么让你的项目更好看?用 UI Lab 练设计原则,给界面去 AI 味
前端·aigc·ai编程
用户693717500138414 小时前
AI 越强,为什么我们反而越来越担心失业?
前端·后端·github
涛涛ing16 小时前
线上突发大面积白屏,排查一天后,我发现是 `JSON.parse` 背了锅
前端
小小小小宇16 小时前
Chrome 扩展如何操作浏览器:chrome.debugger 与 CDP 的区别
javascript
狮子座的男孩16 小时前
javascript 基础 es6:1、let 声明,let 实践案例,const 声明,解构赋值
前端·javascript·经验分享·es6·const声明·解构赋值·let声明及案例