詳解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;
使用
每當輸入框的值發(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只能存儲字符串,當涉及到存儲函數(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 select當前value沒有更新到vue對象屬性的問題
今天小編就為大家分享一篇解決vue select當前value沒有更新到vue對象屬性的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
vue項目如何實現(xiàn)ip和localhost同時訪問
這篇文章主要介紹了vue項目如何實現(xiàn)ip和localhost同時訪問,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10

