localStorage、sessionStorage ES6簡單封裝

localStorage、sessionStorage ES6簡單封裝:

class Store {
  constructor (store) {
    // 檢測是否支持localstorage
    if (!store) {
      console.log('不支持localStorage')
      return
    }
    this._store = store
  }

  /**
   * @function 設置值
   * @param {string} _k 必須參數,屬性
   * @param {any} _v 非必須參數,屬性值
   */
  setItem (_k, _v) {
    if (!this._store) return
    let kType = this.getType(_k)
    if (kType === 'string') {
      this._store.setItem(_k, this.filterValue(_v))
    } else {
      console.log('key只能爲字符串!')
    }
  }

  /**
   * @function 獲取值
   * @param {string} _k 必須參數,屬性
   */
  getItem (_k) {
    if (!this._store) return
    let res
    let kType = this.getType(_k)
    if (kType === 'string') {
      res = this._store.getItem(_k)
    } else {
      console.log('key只能爲字符串!')
    }
    return res
  }

  /**
   * @function 移除值
   * @param {string} _k 必須參數,屬性
   */
  removeItem (_k) {
    if (!this._store) return
    let kType = this.getType(_k)
    if (kType === 'string') {
      res = this._store.removeItem(_k)
    } else {
      console.log('key只能爲字符串!')
    }
  }

  /**
   * @function 移除全部
   */
  clear () {
    if (!this._store) return
    this._store.clear()
  }

  /**
   * @function 判斷類型
   * @param {any} para 必須參數,判斷的值
   */
  getType (para) {
    let type = typeof para
    if (type === 'number' && isNaN(para)) return 'NaN'
    if (type !== 'object') return type
    return Object.prototype.toString
      .call(para)
      .replace(/[\[\]]/g, '') // eslint-disable-line
      .split(' ')[1]
      .toLowerCase()
  }

  /**
   * @function 過濾值
   * @param {any} val 必須參數,過濾的值
   */
  filterValue (val) {
    let vType = this.getType(val)
    let nullVal = ['null', 'undefined', 'NaN']
    let stringVal = ['boolen', 'number', 'string']
    if (nullVal.indexOf(vType) >= 0) return ''
    if (stringVal.indexOf(vType) >= 0) return val
    return JSON.stringify(val)
  }
}

class LocalStorage extends Store {
  constructor (store) { // eslint-disable-line
    super(store)
  }
  WX_USER_ID = 'WX_USER_ID'
}

class SessionStorage extends Store {
  constructor (store) { // eslint-disable-line
    super(store)
  }
  WX_SSO_TITLE = 'WX_SSO_TITLE'
}

const lStorage = new LocalStorage(window.localStorage || localStorage)
const sStorage = new SessionStorage(window.sessionStorage || sessionStorage)

export {
  lStorage,
  sStorage
}

使用方式:

import { lStorage, sStorage } from './storage.js'

lStorage.setItem(lStorage.WX_USER_ID, ['val'])
lStorage.getItem(lStorage.WX_USER_ID) // ['val']
相關文章
相關標籤/搜索