2024-01-25 - JavaScript 系列八:第5課 ── 體重追蹤應用程式-步驟01 繼續 JavaScript 系列八:第5課 ── 體重追蹤應用程式 這次作業的規格如下:
這種程式應該要讓人註冊登入使用,需要後端配合,但我們簡化吧:免登入、把資料存在 local storage 就好 此程式能夠新增一筆體重資料,input 欄位有「體重」、「日期」 有清單列表顯示每一筆輸入的資料,按照日期排序。每筆資料旁邊有刪除按鈕 使用 Chart.js 將體重的走勢,用折線圖(Line Chart)呈現 請「不要」使用社群包裝的版本(vue-chartjs),學著自己在框架內導入套件 請一步步教我,先有個架構即可,我現在是用 vite vue3
太好了!我們一步一步來用 Vite + Vue 3(Composition API)建構這個體重追蹤應用程式,第 5 課的核心目標是:
✅ 使用 localStorage ✅ 可以新增體重和日期 ✅ 顯示清單,按日期排序 ✅ 可刪除 ✅ 使用 Chart.js 畫出折線圖
🧱 第一步:建立基本 Vue 應用架構 我們先完成這些:
建好畫面結構
設計體重資料格式
確保 localStorage 的讀寫沒問題
設定 Chart.js(稍後再畫圖)
✅ 1. 建立基本檔案結構 目標放在 src/lily_learning/202404_js_trainging/javascript_8/weightTrackerApp/
1 2 3 4 5 6 7 8 9 10 src/ └── lily_learning/ └── 202404_js_trainging/ └── javascript_8/ └── weightTrackerApp/ ├── WeightTracker.vue <- 主元件 └── components/ ├── WeightForm.vue <- 表單:新增資料 ├── WeightList.vue <- 清單:顯示 + 刪除 └── WeightChart.vue <- 折線圖
✅ 2. 建立 WeightTracker.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 <!-- src/lily_learning/202404_js_trainging/javascript_8/weightTrackerApp/WeightTracker.vue --> <template> <div class="p-4"> <h1 class="text-xl font-bold mb-4">體重追蹤器</h1> <WeightForm @add-weight="addWeight" /> <WeightList :weights="weights" @delete-weight="deleteWeight" /> <WeightChart :weights="weights" /> </div> </template> <script setup> import { ref, onMounted, watch } from 'vue' import WeightForm from './components/WeightForm.vue' import WeightList from './components/WeightList.vue' import WeightChart from './components/WeightChart.vue' const weights = ref([]) // 載入 localStorage onMounted(() => { const saved = localStorage.getItem('weights') if (saved) { weights.value = JSON.parse(saved) } }) // 寫入 localStorage watch(weights, (newVal) => { localStorage.setItem('weights', JSON.stringify(newVal)) }, { deep: true }) // 新增體重 function addWeight(weightData) { weights.value.push(weightData) // 按日期排序(新到舊) weights.value.sort((a, b) => new Date(b.date) - new Date(a.date)) } // 刪除 function deleteWeight(index) { weights.value.splice(index, 1) } </script>
接下來,我們會一步步建立這 3 個元件:
WeightForm.vue
(輸入)
WeightList.vue
(清單)
WeightChart.vue
(Chart.js 折線圖)