使用 WEB API 的 sessionStorage 儲存 - daniel-qa/Vue GitHub Wiki
如果儲存的資料是一個包含複雜結構的 reactive 物件,在存到sessionStorage 或 localStorage 之前,你需要將它轉換為字串,因為這兩個 API 只能存儲字串資料。
你可以使用 JSON.stringify() 將這個物件轉換成字串儲存,再使用 JSON.parse() 讀取並轉換回物件。這樣不會丟失結構。
// 將 noticeForm 轉換為 JSON 字串並儲存在 sessionStorage 中
sessionStorage.setItem('noticeForm', JSON.stringify(noticeForm))
// 讀取資料並轉回物件
const storedNoticeForm = JSON.parse(sessionStorage.getItem('noticeForm'))
- 使用 Object.assign() 更新 reactive
Object.assign() 是「更新物件內容」;
🔁 直接給值(像 noticeForm = xxx)是「整個物件換掉」!
🧪 假設情境:
const noticeForm = reactive({
title: 'Hello',
body: 'World'
});
✅ 使用 Object.assign() 的效果:
const saved = { title: 'Hi', body: 'Everyone' };
Object.assign(noticeForm, saved);
.setItem
.getItem
.removeItem
<template>
<div>
<el-input
v-model="userName"
placeholder="輸入你的名字"
/>
<el-button @click="saveName">儲存</el-button>
<el-button @click="showName">顯示</el-button>
<el-button @click="clearName">清除</el-button>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const userName = ref('') // 用來綁定輸入框的名稱
const message = ref('') // 顯示結果的訊息
// 儲存名稱到 sessionStorage
function saveName() {
sessionStorage.setItem('userName', userName.value)
message.value = '✅ 名字已儲存!'
}
// 顯示名稱
function showName() {
const savedName = sessionStorage.getItem('userName')
message.value = savedName
? `👋 你好,${savedName}`
: '⚠️ 沒有儲存的名字'
}
// 清除名稱
function clearName() {
sessionStorage.removeItem('userName')
message.value = '🧹 名字已清除'
}
</script>
-
sessionStorage 的生命週期與分頁的開啟與關閉直接掛鉤。
-
localStorage 則是「長期保存」,無論分頁是否關閉,直到手動瀏覽器的歷史資料。