iT邦幫忙

2025 iThome 鐵人賽

DAY 28
0
Vue.js

邊學邊做:Vue.js 實戰養成計畫系列 第 28

Day 28:宇宙觀察日誌 — localStorage 資料保存

  • 分享至 

  • xImage
  •  

我們今天要延續昨天的Final Mission — 5 日實作計畫,設計一個Galactic Explorer!
今日目標:製作「觀察日誌」功能,記錄每日探索心得。

我們要讓「宇宙觀察日誌」能夠永久保存,即使刷新頁面、關掉再開也不會消失~!
我們會用到三個關鍵概念:

  • ref() → 建立反應式變數
  • watchEffect() → 自動偵測變化並保存
  • localStorage → 存在瀏覽器的永久資料空間

1)建立新頁面 Diary.vue

src/views/ 裡新增一個檔案:

<template>
  <main class="diary">
    <h1>🌌 宇宙觀察日誌</h1>

    <!-- 新增日誌輸入區 -->
    <el-input
      v-model="draft"
      type="textarea"
      rows="4"
      placeholder="記錄今天的星際探索心得..."
    />
    <el-button type="primary" @click="saveLog">💾 儲存</el-button>

    <hr />

    <!-- 日誌列表 -->
    <ul class="logs">
      <li v-for="log in logs" :key="log.id">
        <p class="text">{{ log.text }}</p>
        <small class="time">{{ log.time }}</small>
      </li>
    </ul>
  </main>
</template>

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

const draft = ref('')
const logs = ref([])

// ✅ 第一次載入頁面時,從 localStorage 取資料
onMounted(() => {
  const saved = localStorage.getItem('diaryLogs')
  if (saved) {
    try {
      logs.value = JSON.parse(saved)
    } catch (err) {
      console.error('localStorage 格式錯誤:', err)
      logs.value = []
    }
  }
})

// ✅ 當 logs 改變時,更新 localStorage
watch(
  logs,
  (newVal) => {
    localStorage.setItem('diaryLogs', JSON.stringify(newVal))
  },
  { deep: true } // 深層監聽,確保每次內容變化都會保存
)

// ✅ 儲存新日誌
function saveLog() {
  if (!draft.value) return
  logs.value.unshift({
    id: Date.now(),
    text: draft.value,
    time: new Date().toLocaleString()
  })
  draft.value = ''
}
</script>

<style scoped>
.diary {
  max-width: 700px;
  margin: auto;
  padding: 20px;
  font-family: 'Orbitron', system-ui;
  color: #e0e7ff;
}
.logs {
  list-style: none;
  padding: 0;
}
.logs li {
  background: rgba(167, 139, 250, 0.1);
  border: 1px solid rgba(167, 139, 250, 0.3);
  border-radius: 12px;
  padding: 12px;
  margin-top: 12px;
}
.text {
  margin: 0 0 4px;
  font-size: 1.1em;
}
.time {
  font-size: 0.85em;
  color: #a78bfa;
}
</style>

2)在 Router 中註冊 /diary 路由

開啟 src/router/index.js,在 routes 陣列中加入:

import Diary from '../views/Diary.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', name: 'home', component: Home },
    { path: '/planets', name: 'planets', component: Planets },
    { path: '/diary', name: 'diary', component: Diary }, // ✨ 新增這行
    { path: '/:pathMatch(.*)*', name: '404', component: NotFound }
  ]
})

3)在導航列加入日誌連結

App.vue(或 Navbar 元件)加上:

<router-link to="/diary">🪐 宇宙觀察日誌</router-link>

https://ithelp.ithome.com.tw/upload/images/20251010/20178644zcjUuBxB6t.png
如此重新整理頁面後資料仍會存在!

參考資源
https://vuejs.org/guide
https://www.runoob.com/vue3


上一篇
Day 27:星球資料艙 — 星球知識頁 (v-for + 動態路由)
下一篇
Day 29:生物探測器 — 小遊戲(v-if / v-for / methods / emit)
系列文
邊學邊做:Vue.js 實戰養成計畫30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言