• 在Vue 3中使用useStorage轻松实现localStorage功能


    在Vue 3中使用useStorage轻松实现localStorage功能

    VueUse 介绍

    VueUse文档:Get Started | VueUse

    VueUse是基于Vue3的Composition API的实用函数的集合,useStorage是其中的一个函数。我们可以使用useStorage来实现我们的localStorage功能。

    安装

    npm i @vueuse/core
    

    使用CDN

    1. <script src="https://unpkg.com/@vueuse/shared">script>
    2. <script src="https://unpkg.com/@vueuse/core">script>

    useStorage()的用法

    useStorage()将要用于引用的键名作为第一个参数传递,将要保存的值作为第二个参数传递。

    值的保存、获取、删除

    localStorage设置setItem()来保存值,用getItem()来获取值,用removeItem来删除值如下:

    useStorage()只需要一个就可以进行值的保存和获取,如下,用法:

    const storedValue = useStorage('key', value)
    

    例子:

    1. const msg = ref('你好')
    2. //保存值
    3. useStorage('msg',msg.value)
    4. //获取值
    5. const msgData = useStorage('msg')
    6. console.log('msgData',msgData.value)
    7. //删除
    8. const clear = () => {
    9. msg.value = null
    10. }

    useStorage()自定义序列化

    默认情况下,useStorage将根据提供的默认值的数据类型智能地使用相应的序列化程序。例如,JSON.stringify/JSON.parse将用于对象,Number.toString/parseFloat用于数字等。 如下:

    1. import { useStorage } from '@vueuse/core'
    2. useStorage(
    3. 'key',
    4. {},
    5. undefined,
    6. {
    7. serializer: {
    8. read: (v: any) => v ? JSON.parse(v) : null,
    9. write: (v: any) => JSON.stringify(v),
    10. },
    11. },
    12. )

    以上代码,我们设置对象的名称为key,初始值为空对象{},如果存储中没有key的值,则返回null。在写入时,将对象序列化为JSON字符串。

  • 相关阅读:
    pinia——打败vuex的新一代vue存储库
    抖音实战~分享模块~复制短视频链接
    Dolphin Scheduler 2.x版本部署篇
    开源与闭源:AI模型发展路径的选择与权衡
    Linux这么在两个服务器直接传文件?
    嵌入式设备时间同步(校时)
    数组更新检测
    MySQL基本操作(CRUD)详解
    171-178-Hadoop-源码
    车载诊断新驱动——远程诊断
  • 原文地址:https://blog.csdn.net/qq_48652579/article/details/130660186