vue工具类之——LocalStorage操作(完整复杂版本)

早之前在CSDN上发布过类似的,这次整理项目时候,重新整理了一下:


/**

* description: LocalStorage

* create_time: 2017-04-02

* message: 不接受任何私下吐槽,请当面沟通协调

*/

import extend from 'Extend';

import urlParam from './URLParam'

class LocalStorage {

  constructor(STORAGE_KEY) {

    this.date= new Date();

   this.STORAGE_KEY= (STORAGE_KEY)?{PAGE_PARA: STORAGE_KEY} : {PAGE_PARA: window.location.host};

  };

  get(key) {

    let store = localStorage.getItem(key);

    if (store) {

      try {

        store = JSON.parse(store);

      } catch (e) {

        store = undefined;

        this.del(key);

      }

}

    return Promise.resolve(store || {})

  };

  del(key) {

    localStorage.removeItem(key);

  };

  set(key, value) {

    localStorage.setItem(key, JSON.stringify(value));

    return Promise.resolve(value);

  };

  put(key, value) {

    let me = this;

    return this.get(key).then(data=> {

      value= extend(data|| {}, value|| {});

      return me.set(key, value)

})

  };

  getParam(key) {

    let UrlParam = new urlParam();

    return this.get(this.STORAGE_KEY.PAGE_PARA).then(data=> {

      data= data|| {};

      return extend(data[key], UrlParam.getURLParam())

})

  };

  setParam(key, para) {

    let me = this;

    return this.get(this.STORAGE_KEY.PAGE_PARA).then(data=> {

      data= data|| {};

      data[key] = para;

      return me.set(this.STORAGE_KEY.PAGE_PARA, data)

})

  };

  putParam(key, para) {

    let me = this;

    return this.get(this.STORAGE_KEY.PAGE_PARA).then(data=> {

      data= data|| {};

      data[key] = extend((data[key] || {}), para);

      return me.set(this.STORAGE_KEY.PAGE_PARA, data)

})

  };

  removeSubParam(key, subKey) {

    let me = this;

    return this.get(this.STORAGE_KEY.PAGE_PARA).then(data=> {

      if (data) {

        delete data[key][subKey];

        return me.set(this.STORAGE_KEY.PAGE_PARA, data);

      }

})

}

}

export default LocalStorage


用法实例:

let local = new LocalStorage('ra.com');
local.set('home', {a: 'A-A', b: 'B-B'});
local.setParam('home', {a: 'A-A', b: 'B-B'})
const a = local.getParam('home')

a.then(data=>{
    console.log(data)
})

简化版本,请移步:CSDN 晚些时间,我会逐步把CSDN的博客整理过来!

你可能感兴趣的:(vue工具类之——LocalStorage操作(完整复杂版本))