Local Storage 雖可在瀏覽器端儲存資料,唯都是 String 處理,若要儲存 Boolean,需要些技巧處理。
Version
Vue 3.2
Boolean for Local Storage
<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(true)
let onWrite = () => {
localStorage.setItem('checked', false)
}
let onRead = () => {
result.value = JSON.parse(localStorage.getItem('checked'))
}
</script>
12 行
let onWrite = () => {
localStorage.setItem('checked', false)
}
- 直接透過
localStorage.setItem()
將 Boolean 寫入 local storage 即可,此時會以 String 的false
寫入 local storage
16 行
let onRead = () => {
result.value = JSON.parse(localStorage.getItem('checked'))
}
- 以
localStorage.getItem()
從 local storage 讀出,此時讀出為 String,可再透過JSON.parse()
從 String 轉成 Boolean
Conclusion
- 整個解法
JSON.parse()
,它可將true
與false
由 String 轉成 Boolean