• 封装localStorage,支持切换存储引擎 sessionStorage,支持vue hook方式调用


    封装storage存储class

    // MyStorage.ts
    export enum StorageType {
      session = 'session',
      local = 'local'
    }
    export class MyStorage {
      /** 存储key值前缀 */
      private prefix: string
      /** 单例的实例 */
      private static _instance: Map<string, MyStorage>
      private storage: Storage
      private engine = {
        [StorageType.session]: sessionStorage,
        [StorageType.local]: localStorage
      }
      // 单例模式
      constructor(prefix = '', type: StorageType = StorageType.local) {
        this.prefix = prefix
        this.storage = this.engine[type]
        if (!this.storage) {
          throw new Error("engine type error. it must be 'session','local'")
        }
        if (!MyStorage._instance) {
          MyStorage._instance = new Map()
        }
        if (!MyStorage._instance?.has(type)) {
          MyStorage._instance.set(type, this)
        }
        return MyStorage._instance.get(type) as MyStorage
      }
    
      private getFullKey(value: string) {
        return this.prefix + value
      }
      /**
       *
       * @param key
       * @param value
       * @param expire 过期时间,单位秒,默认0,永不过期
       * @returns
       */
      set(key: string, value: any, expire = 0) {
        try {
          const wrapData = {
            value,
            expire,
            time: Date.now() // 保存时间
          }
          const data = JSON.stringify(wrapData)
          this.storage.setItem(this.getFullKey(key), data)
          return true
        } catch (error) {
          console.error(error)
          return false
        }
      }
      /**
       * 追加对象保持
       * @param key
       * @param value
       * @param expire
       * @returns
       */
      setInto(key: string, value: Record<string, any>, expire = 0) {
        try {
          const preData = this.get(key)
          const wrapData = {
            value,
            expire,
            time: Date.now() // 保存时间
          }
          if (preData) {
            Object.assign(wrapData.value, preData, value)
          }
          const data = JSON.stringify(wrapData)
          this.storage.setItem(this.getFullKey(key), data)
          return true
        } catch (error) {
          console.error(error)
          return false
        }
      }
      /**
       * 获取值
       * @param key
       * @returns
       */
      get(key: string) {
        try {
          const localData = this.storage.getItem(this.getFullKey(key))
          if (localData === null) return localData
          const data = JSON.parse(localData)
          if (data.expire > 0 && Date.now() - data.time > data.expire * 1000) {
            // js时间戳是ms,13位数
            this.remove(key)
            return null
          }
          return data.value
        } catch (error) {
          console.error(error)
          return null
        }
      }
      /**
       *  remove a value of key
       * @param key
       */
      remove(key: string) {
        this.storage.removeItem(this.getFullKey(key))
      }
    
      /**
       * clear all value of the prefix key
       */
      clear(): void {
        Object.keys(this.storage).forEach(key => {
          if (key.startsWith(this.prefix)) {
            this.storage.removeItem(key)
          }
        })
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123

    封装 vue hook

    // @/hook/useStorage.ts
    import { MyStorage, StorageType } from 'MyStorage.ts'
    import { ref} from 'vue'
    
    export const useStorage = (key: string, prefix = 'test_', type = 'local') => {
      const storageHandle = new MyStorage(prefix, type as StorageType)
    
      const value = ref(storageHandle.get(key))
      const setValue = (storage: any) => {
        return (newValue: any) => {
          value.value = newValue
          storage.set(key, newValue)
        }
      }
      return [value, setValue(storageHandle), storageHandle]
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    vue中使用

    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
  • 相关阅读:
    性能问题从发现到优化一般思路
    晶振工作原理详解
    Linux起源
    Ruby 数据库访问 - DBI 教程
    @Controller和@RestController的区别
    Docker Desktop 设置镜像环境变量
    pandas时间序列之 pd.to_datetime()
    Mysql——压缩包方式安装教程
    从0开始的异世界编程 [3]
    vue课程79 介绍并安装vue-cli
  • 原文地址:https://blog.csdn.net/example440982/article/details/133686358