做展柜平时在哪里网站推广,网站色彩学,链友之家,php做学校网站免费我们经常需要使用 LocalStorage API#xff0c;一个好用的可组合函数封装将帮助我们更好地使用它#xff0c;让我们开始吧 #x1f447;:
script setup langtsimport { ref, watch } from vue/*** Implement the composable function* Make sure the f… 我们经常需要使用 LocalStorage API一个好用的可组合函数封装将帮助我们更好地使用它让我们开始吧 :
script setup langtsimport { 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/scripttemplatepCounter: {{ counter }}/pbutton clickupdateUpdate/button
/template其中的watch可以修改为以下方式
watchEffect(() {localStorage.setItem(key, value.value)
})// watchEffect自动添加了immediate:true
watchEffect立即运行一个函数同时响应式地追踪其依赖并在依赖更改时重新执行。
watchEffect的特点可以查看watchEffect()和effectScope()-CSDN博客