Vite+Vue3 项目 华仔待办

此“华仔”,不是彼“华仔”,你懂的!

先来了个截图

紧跟着,实现步骤也来了

1. 安装 Node.js,终端运行 npm create vue@latest,项目名 vue-to-do,后面的选项全选 No

2. cd vue-to-do 进入项目目录,npm install 安装依赖,npm run dev 启动 Vite 开发服务器;

3. 修改 index.htmlmain.js

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>华仔待办</title>
  </head>
  <body>
    <!-- 根组件容器 -->
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

src/main.js

import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'
// 创建应用 传根组件
createApp(App).mount('#app')

4. 修改 App.vue 根组件,添加 ToDoHead.vue ToDoBody.vue 两个子组件;

src/App.vue

<script setup>
import ToDoHead from './components/ToDoHead.vue';
import ToDoBody from './components/ToDoBody.vue';
</script>

<template>
  <ToDoHead />
  <ToDoBody />
</template>

<style scoped>
</style>

src/components/ToDoHead.vue

<script setup>
</script>

<template>
  <h1>华仔待办</h1>
</template>

<style scoped>
</style>

src/components/ToDoBody.vue

<script setup>
import { ref } from 'vue';
let tasks = ref([])  // ref 对象 任务列表 { name: '任务名', state: '状态' } active completed
let taskName = ref("")  // ref 对象 .value
// 添加任务
function addTask() {
  if (taskName.value.trim() === "") {
    return
  }
  tasks.value.push({
    name: taskName.value,
    state: 'active'
  })
  taskName.value = ""
}
// 完成任务
function completeTask(index) {
  tasks.value[index].state = 'completed'
}
// 删除任务
function deleteTask(index) {
  tasks.value.splice(index, 1)
}
// 删除所有
function deleteAll() {
  tasks.value.splice(0, tasks.value.length)
}
</script>

<template>
  <input type="text" placeholder="请输入任务" v-model="taskName" v-on:keyup.enter="addTask">
  <p v-if="tasks.length === 0">还没有任务,请添加。</p>
  <div>
    <p v-for="(task,index) in tasks" v-bind:class="task.state" v-on:click="completeTask(index)" v-on:dblclick="deleteTask(index)">{{ index+1 }}. {{ task.name }}</p>
  </div>
  <span class="stats">共 {{ tasks.length }} 个</span> <button v-on:click="deleteAll">清理</button>
</template>

<style scoped>
</style>

5. 修改 main.css 页面样式;

src/assets/main.css

.stats {
  color: #888;
}
.completed {
  color: #888;
  text-decoration: line-through;
}

What?You can't understand?

问时迟,那时快。这五个步骤突然化身为五枚金币,不慢不快地,躲进一个金光闪闪的“宝盒”里。大侠!还不快去 take 走?