美文网首页
本地存储方法

本地存储方法

作者: Sasoli | 来源:发表于2018-12-11 16:17 被阅读0次
/**
  封装本地存储
*/
let store = {
  storage: window.localStorage,
  session: {
    storage: window.sessionStorage
  }
}

const api = {
  set (key, val) {
    if (this.disabled) {
      return
    }
    if (val === undefined) {
      return this.remove(key)
    }
    this.storage.setItem(key, serialize(val))
    return val
  },

  get (key, def) {
    if (this.disabled) {
      return def
    }
    let val = deserialize(this.storage.getItem(key))
    return (val === undefined ? def : val)
  },

  has (key) {
    return this.get(key) !== undefined
  },

  remove (key) {
    if (this.disabled) {
      return
    }
    this.storage.removeItem(key)
  },

  clear () {
    if (this.disabled) {
      return
    }
    this.storage.clear()
  },

  getAll () {
    if (this.disabled) {
      return null
    }
    let ret = {}
    this.forEach((key, val) => {
      ret[key] = val
    })
    return ret
  },

  forEach (callback) {
    if (this.disabled) {
      return
    }
    for (let i = 0; i < this.storage.length; i++) {
      let key = this.storage.key(i)
      callback(key, this.get(key))
    }
  }
}

Object.assign(store, api)

Object.assign(store.session, api)

function serialize (val) {
  return JSON.stringify(val)
}

function deserialize (val) {
  if (typeof val !== 'string') {
    return undefined
  }
  try {
    return JSON.parse(val)
  } catch (e) {
    return val || undefined
  }
}

export default store

常用方式:

import storage from './utils/storage.js';

let value = {
  name: 111,
  age: 22,
}
//存储
storage.session.set('myValue', value);
//取出
storage.session.get('myValue')

相关文章

网友评论

      本文标题:本地存储方法

      本文链接:https://www.haomeiwen.com/subject/gzlehqtx.html