@vue-material/core
Version:
Yet another 'Material Design Components' library for Vue3.
31 lines (30 loc) • 856 B
JavaScript
import { parser, stringify } from "../utils/object/transform.js";
import { ref, onMounted, onUnmounted, watch } from "vue";
function useLocalStorage(key, defaultValue) {
let ignore = true;
const value = ref(defaultValue);
function getData() {
const data = localStorage.getItem(key);
return data ? parser(data) : defaultValue;
}
function handleDataChange(event) {
if (event.key === key) {
ignore = true;
value.value = getData();
}
}
function watcher(data) {
if (ignore) return ignore = false;
localStorage.setItem(key, stringify(data));
}
onMounted(() => {
value.value = getData();
addEventListener("storage", handleDataChange);
});
onUnmounted(() => removeEventListener("storage", handleDataChange));
watch(value, watcher, { deep: true });
return value;
}
export {
useLocalStorage
};