2025-01-26- JavaScript 系列八:第5課 ── 體重追蹤應用程式-步驟02

2025-01-26- JavaScript 系列八:第5課 ── 體重追蹤應用程式-步驟02

「體重追蹤應用程式」基本架構。


✅ 第一步:設定基本架構與資料儲存(localStorage)

先做以下幾件事:

  1. 建立表單輸入體重與日期。
  2. 把資料儲存到 localStorage。
  3. 顯示已儲存的資料清單。
  4. 可以刪除清單中的資料。

📁 WeightTrackerApp.vue 架構草稿:

請在你的 WeightTrackerApp.vue 中輸入以下內容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<template>
<div class="p-4 max-w-md mx-auto">
<h1 class="text-2xl font-bold mb-4">體重追蹤器</h1>

<!-- 輸入表單 -->
<form @submit.prevent="addRecord" class="space-y-2 mb-4">
<div>
<label>日期:</label>
<input type="date" v-model="newRecord.date" class="border px-2 py-1" required />
</div>
<div>
<label>體重(kg):</label>
<input type="number" v-model.number="newRecord.weight" class="border px-2 py-1" required />
</div>
<button type="submit" class="bg-blue-500 text-white px-4 py-1 rounded">新增</button>
</form>

<!-- 清單 -->
<ul class="space-y-2">
<li v-for="(record, index) in sortedRecords" :key="record.id" class="flex justify-between items-center border p-2">
<span>{{ record.date }} - {{ record.weight }} kg</span>
<button @click="deleteRecord(record.id)" class="text-red-500">刪除</button>
</li>
</ul>
</div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'

const newRecord = ref({
date: '',
weight: null,
})

const records = ref([])

// 初始化資料
onMounted(() => {
const saved = localStorage.getItem('weight-records')
if (saved) {
records.value = JSON.parse(saved)
}
})

// 監看資料變化自動存入 localStorage
watch(records, (newVal) => {
localStorage.setItem('weight-records', JSON.stringify(newVal))
}, { deep: true })

const addRecord = () => {
if (!newRecord.value.date || !newRecord.value.weight) return

records.value.push({
id: Date.now(),
date: newRecord.value.date,
weight: newRecord.value.weight,
})

newRecord.value = { date: '', weight: null }
}

const deleteRecord = (id) => {
records.value = records.value.filter(r => r.id !== id)
}

const sortedRecords = computed(() => {
return [...records.value].sort((a, b) => new Date(a.date) - new Date(b.date))
})
</script>

✅ 這一步完成後,你會有什麼功能?

  • 使用者可以輸入日期和體重
  • 可以新增資料、顯示清單、刪除資料
  • 所有資料都會存在 localStorage 裡,不會遺失