MemorizeVar.ts 396 B

123456789101112131415161718
  1. import { onMounted, ref, watch } from "vue";
  2. export function memorizeVar<T>(key: string, defaultValue: T) {
  3. const variable = ref<T>(defaultValue);
  4. onMounted(() => {
  5. const v = localStorage.getItem(key);
  6. if (v)
  7. variable.value = JSON.parse(v);
  8. });
  9. watch(variable, (newValue) => {
  10. localStorage.setItem(key, JSON.stringify(newValue));
  11. });
  12. return {
  13. variable
  14. };
  15. }