此“華仔”,不是彼“華仔”,你懂的!
先來了個截圖
緊跟著,實現步驟也來了
1. 安裝 Node.js
,終端執行 npm create vue@latest
,專案名 vue-to-do
,後面的選項全選 No
;
2. cd vue-to-do
進入專案目錄,npm install
安裝依賴,npm run dev
啟動 Vite
開發伺服器;
3. 修改 index.html
和 main.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 走?