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

18 - 实现本地存储函数

Open kalu5 opened this issue 2 years ago • 0 comments

// 你的答案
<script setup lang='ts'>

import { ref, watch, unref, Ref } from "vue"

/**
 * Implement the composable function
 * Make sure the function works correctly
*/
function useLocalStorage(key: string, initialValue: T | Ref<T>) {
  initialValue = localStorage.getItem(key) || initialValue
  const value = ref(initialValue)
  watch(value, (newVal) => { 
    localStorage.setItem(key, unref(newVal))
  })
  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>

kalu5 avatar Sep 15 '22 01:09 kalu5