Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Gorvey opened this issue May 7, 2024 · 0 comments
Open

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

Gorvey opened this issue May 7, 2024 · 0 comments

Comments

@Gorvey
Copy link

Gorvey commented May 7, 2024

<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant