教你在Vue3中使用useStorage轻松实现localStorage功能
作者:Emo_TT
VueUse 介绍
VueUse文档:Get Started | VueUse
VueUse是基于Vue3的Composition API的实用函数的集合,useStorage是其中的一个函数。我们可以使用useStorage来实现我们的localStorage功能。
安装
npm i @vueuse/core
使用CDN
<script src="https://unpkg.com/@vueuse/shared"></script> <script src="https://unpkg.com/@vueuse/core"></script>
useStorage()的用法
useStorage()将要用于引用的键名作为第一个参数传递,将要保存的值作为第二个参数传递。
值的保存、获取、删除
localStorage设置setItem()来保存值,用getItem()来获取值,用removeItem来删除值如下:
<script setup >
import {ref} from "vue";
const counter = ref('消息')
//保存值
localStorage.setItem('counter',counter.value)
//获取值
const data = localStorage.getItem('counter')
console.log('data',data)
//删除值
localStorage.removeItem('counter')
</script>而useStorage()只需要一个就可以进行值的保存和获取,如下,用法:
const storedValue = useStorage('key', value)例子:
const msg = ref('你好')
//保存值
useStorage('msg',msg.value)
//获取值
const msgData = useStorage('msg')
console.log('msgData',msgData.value)
//删除
const clear = () => {
msg.value = null
}useStorage()自定义序列化
默认情况下,useStorage将根据提供的默认值的数据类型智能地使用相应的序列化程序。例如,JSON.stringify/JSON.parse将用于对象,Number.toString/parseFloat用于数字等。 如下:
import { useStorage } from '@vueuse/core'
useStorage(
'key',
{},
undefined,
{
serializer: {
read: (v: any) => v ? JSON.parse(v) : null,
write: (v: any) => JSON.stringify(v),
},
},
)以上代码,我们设置对象的名称为key,初始值为空对象{},如果存储中没有key的值,则返回null。在写入时,将对象序列化为JSON字符串。
补充知识:Vue_localStorage本地存储和本地取值解决方法。
Vue本地存储(3种)
① localStorage(长期存储)
存:localStorage.setitem('key',data)
取:localStorage.getitem('key')
② sessionStorage(临时存储)
存:sessionStorage.setitem('key',data)
取:sessionStorage.getitem('key')
③ cookie(有时效性)
一、共同点:
①都可以存储,并且存储只跟域名走、只存储在当前域名下。
二、不同点:
▶存储大小不同
①localStoage/sessionStorage /5M
②cookie /4K 有时效性 如果没有设置时间会话关闭自动失效
③localStorage/不主动删除,数据一直在。
④sessionStorage/在浏览器打开期间存在,关闭当前会话即清空(刷新不清除)
sessionStorage和localStorage用法基本一致,引用类型的值需要转换成Json,我这里用localstorage来举例。

总结
到此这篇关于在Vue3中使用useStorage轻松实现localStorage功能的文章就介绍到这了,更多相关Vue3实现localStorage功能内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
