当前位置:   article > 正文

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

usestorage使用sessionstorange

封装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中使用

<script setup lang="ts">
import {useStorage} from '@/hook/useStorage'
onMounted(() => {
  let [value2, setValue2, b] = useStorage('b', 'prefix_')
  let [value3, setValue3, c] = useStorage('c', 'prefix_')
  let [value, setValue, a] = useStorage('a', 'test2_', 'session')
  console.log('c === b', b === c)
  console.log('storage1', value)
  console.log('storage2', value2)
  setValue({
    age: 18,
    name: 'lili',
    famary: {
      p1: '11',
      p2: '22',
    }
  })
  setValue2({
  b: 'bb'
  })
  setTimeout(() => {
    setValue3({
      c: 'after fetch save'
    })
    console.log('set storage1', value)
    console.log('set storage2', value2)
    console.log('set storage3', value3)
  }, 3000)
})
</script>
  • 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
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/487404
推荐阅读
相关标签
  

闽ICP备14008679号