我们经常需要使用 LocalStorage API,一个好用的可组合函数封装将帮助我们更好地使用它,让我们开始吧 👇:
<script setup lang='ts'>
import { ref, watch } from "vue"
/**
 * Implement the composable function
 * Make sure the function works correctly
*/
function useLocalStorage(key: string, initialValue: any) {
  const value = ref(initialValue)
  watch(value,(val)=>{
    localStorage.setItem(key,val)
  },{
    immediate:true
  })
  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>
 
其中的watch可以修改为以下方式:
watchEffect(() => {
    localStorage.setItem(key, value.value)
})
// watchEffect自动添加了immediate:true 
watchEffect:立即运行一个函数,同时响应式地追踪其依赖,并在依赖更改时重新执行。
watchEffect的特点可以查看watchEffect()和effectScope()-CSDN博客










