使用TypeScript封装一个localStorage

最近后台项目需要使用localStorage,参考nova-admin项目封装了下

封装

// src/utils/storage.ts

// key前缀, 可以自定义
const STORAGE_PREFIX = 'riverblog_'

interface StorageData {
  value: any
  expire: number | null
}

/**
 * 本地存储相关操作
 *
 * @return 存储相关操作方法
 */
function createLocalStorage() {
  // 新增本地存储
  function set(key: string, value: any, expire: (number | null) = null) {
    const storageData: StorageData = {
      value,
      expire: null,
    }
    if (expire) {
      storageData.expire = new Date().getTime() + expire * 1000
    }
    const localJson = JSON.stringify(storageData)
    window.localStorage.setItem(`${STORAGE_PREFIX}${String(key)}`, localJson)
  }

  // 获取本地存储
  function get(key: string) {
    const localJson = window.localStorage.getItem(`${STORAGE_PREFIX}${key}`)
    if (!localJson) {
      return null
    }

    const storageData = JSON.parse(localJson)

    if (storageData) {
      const { value, expire } = storageData
      if (expire === null || expire >= Date.now()) {
        return value
      }
    }

    remove(key)
    return null
  }

  // 移除本地存储
  function remove(key: string) {
    window.localStorage.removeItem(`${STORAGE_PREFIX}${key}`)
  }

  // 清除本地存储
  function clear() {
    window.localStorage.clear()
  }

  return {
    set,
    get,
    remove,
    clear,
  }
}

export const local = createLocalStorage()

导入

先在src/utils/index.ts导入:

// 存储相关
export * from './storage'

后在组件中使用:

import { local } from '@/utils'

const localOrder = local.get('card_order')
// ...

结尾

写Vue3 + Ts 的后台项目可参考nova-admin,只进行了适当的封装,适合阅读。不像vben等项目层层封装,看起来费劲。

评论