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

18 - 实现本地存储函数

Open slowpack opened this issue 1 year ago • 0 comments

<script setup lang='ts'>
import { ref } from "vue"
function useLocalStorage(key: string, initialValue: any) {
  const save = window.localStorage.getItem(key)
  const value = ref(save??initialValue)
  watchEffect(()=>{
    window.localStorage.setItem(key,value.value)
  })
  return value
}
const counter = useLocalStorage("counter", 0)
const update = () => counter.value++
</script>
<template>
  <p>Counter: {{ counter }}</p>
  <button @click="update">
    Update
  </button>
</template>

slowpack avatar Feb 01 '24 08:02 slowpack