webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.69k stars 188 forks source link

18 - 实现本地存储函数 #2709

Open Gorvey opened 3 months ago

Gorvey commented 3 months ago
<script setup lang="ts">
import { ref, watch, computed } from 'vue';

/**
 * Implement the composable function
 * Make sure the function works correctly
 */
function useLocalStorage(key: string, initialValue: any) {
  let value = ref(initialValue);
  const read = () => {
    const rawValue = localStorage.getItem(key);
    if (rawValue != null) {
      value.value = ref(Number(rawValue));
    }
  };
  read();
  watch(
    () => value.value,
    () => {
      localStorage.setItem(key, value.value);
    }
  );
  return value;
}

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>