詳解Vue3中useLocalStorage的用法
基礎(chǔ)封裝
- 初始化數(shù)據(jù),如果
localStorage
中已有對應(yīng)的數(shù)據(jù)則使用localStorage
的值 - 使用
onMounted
來確保組件已經(jīng)掛載后再執(zhí)行操作 - 為
data
添加一個監(jiān)聽器 - 監(jiān)聽
data
的變化,并將新值保存到localStorage
import { ref, onMounted, watchEffect } from 'vue'; function useLocalStorage(key, defaultValue) { const data = ref(localStorage.getItem(key) || defaultValue); onMounted(() => { const localStorageUpdate = () => { localStorage.setItem(key, data.value); }; watchEffect(localStorageUpdate); }); return data; } export default useLocalStorage;
使用
每當(dāng)輸入框的值發(fā)生變化時,它會自動更新localStorage,并且如果你刷新頁面,它會保留之前的值。
<template> <el-input v-model="text" /> {{ text }} </template> <script lang="ts" setup> import { ref } from "vue"; import useLocalStorage from "../hooks/useLocalStorage.js"; const text = useLocalStorage("myText", "Default Text"); </script>
支持更多數(shù)據(jù)類型
因為localStorage只能存儲字符串,當(dāng)涉及到存儲函數(shù)(function類型)或其他非字符串/JSON類型數(shù)據(jù)時,需要特殊處理。在存儲和檢索函數(shù)時,將其序列化為字符串,然后在檢索時反序列化。
import { ref, onMounted, watchEffect } from "vue"; function useLocalStorage(key, defaultValue) { const storedValue = localStorage.getItem(key); const data = ref(storedValue ? deserialize(storedValue) : defaultValue); onMounted(() => { const localStorageUpdate = () => { localStorage.setItem(key, serialize(data.value)); }; watchEffect(localStorageUpdate); }); // 反序列化數(shù)據(jù) function deserialize(value) { try { const deserialized = JSON.parse(value); if (typeof deserialized === "object" && deserialized !== null) { return deserialized; } else if (typeof deserialized === "function") { return new Function(`return ${deserialized}`)(); } else { return deserialized; } } catch (e) { return value; } } // 序列化數(shù)據(jù) function serialize(value) { if (typeof value === "function") { return value.toString(); } else if (Array.isArray(value)) { return JSON.stringify(value); } else if (typeof value === "object" && value !== null) { return JSON.stringify(value); } else { return value; } } return data; } export default useLocalStorage;
到期刪除
在現(xiàn)有的自定義useLocalStorage
hook 中增加一個配置項,以控制數(shù)據(jù)的有效期。
onMounted
,向 localStorage
中設(shè)置時間戳
localStorage.setItem(`${key}_timestamp`, Date.now().toString());
使用 setInterval
,在組件的生命周期內(nèi)定期檢查數(shù)據(jù)是否過期,然后在過期時手動刪除它。
onMounted(() => { localStorage.setItem(`${key}_timestamp`, Date.now().toString()); //.... const checkExpiration = () => { if ( expiration && storedTimestamp && Date.now() - parseInt(storedTimestamp) > expiration ) { localStorage.removeItem(key); localStorage.removeItem(`${key}_timestamp`); } }; setInterval(checkExpiration, 1000); });
完整代碼:
import { ref, onMounted, watchEffect } from "vue"; function useLocalStorage(key, defaultValue, expiration) { const storedValue = localStorage.getItem(key); const storedTimestamp = localStorage.getItem(`${key}_timestamp`); const data = ref(storedValue ? deserialize(storedValue) : defaultValue); onMounted(() => { localStorage.setItem(`${key}_timestamp`, Date.now().toString()); const localStorageUpdate = () => { localStorage.setItem(key, serialize(data.value)); }; watchEffect(localStorageUpdate); const checkExpiration = () => { if ( expiration && storedTimestamp && Date.now() - parseInt(storedTimestamp) > expiration ) { localStorage.removeItem(key); localStorage.removeItem(`${key}_timestamp`); } }; setInterval(checkExpiration, 1000); }); // 反序列化數(shù)據(jù) function deserialize(value) { try { const deserialized = JSON.parse(value); if (typeof deserialized === "object" && deserialized !== null) { return deserialized; } else if (typeof deserialized === "function") { return new Function(`return ${deserialized}`)(); } else { return deserialized; } } catch (e) { return value; } } // 序列化數(shù)據(jù) function serialize(value) { if (typeof value === "function") { return value.toString(); } else if ( Array.isArray(value) || (typeof value === "object" && value !== null) ) { return JSON.stringify(value); } else { return value; } } return data; } export default useLocalStorage;
到此這篇關(guān)于詳解Vue3中useLocalStorage的用法的文章就介紹到這了,更多相關(guān)Vue3 useLocalStorage內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在 Vue 3 中設(shè)置 `@` 指向根目錄的幾種常見方法匯總
在 Vue 3 項目開發(fā)中,為了方便管理和引用文件路徑,設(shè)置 @ 指向根目錄是一項常見的需求,下面給大家分享在Vue3中設(shè)置 `@` 指向根目錄的方法匯總,感興趣的朋友一起看看吧2024-06-06使用vue.js在頁面內(nèi)組件監(jiān)聽scroll事件的方法
今天小編就為大家分享一篇使用vue.js在頁面內(nèi)組件監(jiān)聽scroll事件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09Vue動態(tài)設(shè)置img的src不生效的問題解決
本文主要介紹了Vue動態(tài)設(shè)置img的src不生效的問題解決,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-01-01vxe-list?vue?如何實現(xiàn)下拉框的虛擬列表
這篇文章主要介紹了vxe-list?vue?如何實現(xiàn)下拉框的虛擬列表,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06