若要讀寫 local storage,可直接使用 Web API 自帶的 function。
Version
Vue 3.3
Simple Read & Write
<template>
<button @click="onWrite">Write Local Storage</button>
<button @click="onRead">Read Local Storage</button>
{{ result }}
</template>
<script setup>
import { ref } from 'vue'
let result = ref('')
let onWrite = () => {
localStorage.setItem('message', 'Hello World')
}
let onRead = () => {
result.value = localStorage.getItem('message')
}
</script>
12 行
let onWrite = () => {
localStorage.setItem('message', 'Hello World')
}
- **localStorage.setItem()**:寫入 local storage
- keyName:傳入 local storage 的 key
- keyValue:傳入 local storage 的 value
16 行
let onRead = () => {
result.value = localStorage.getItem('message')
}
- **localStorage.setItem()**:讀取 local storage
- keyName:傳入 local storage 的 key
Conclusion
- Local storage 會以 string 形式寫入,其他型別如 Number、Boolean 需特別小心