vuejs-challenges icon indicating copy to clipboard operation
vuejs-challenges copied to clipboard

18 - 实现本地存储函数

Open GazzyLifeSense opened this issue 1 year ago • 0 comments

<script setup lang="ts">
import { customRef } from 'vue';

function useLocalStorage(key: string, initialValue: any) {
  return customRef((track, trigger) => ({
    get() {
      // track the latest value
      track();
      const cachedValue = parseInt(localStorage.getItem(key));
      return isNaN(cachedValue) ? initialValue : cachedValue;
    },
    set(val: any) {
      localStorage.setItem(key, val);
      // trigger value update
      trigger();
    },
  }));
}

const counter = useLocalStorage('counter', 0);

// We can get localStorage by triggering the getter:
console.log(counter.value);

// And we can also set localStorage by triggering the setter:

const update = () => counter.value++;
</script>

<template>
  <p>Counter: {{ counter }}</p>
  <button @click="update">Update</button>
</template>

GazzyLifeSense avatar Jan 10 '24 09:01 GazzyLifeSense