获取本地存储的方法

  /**
   * @param {type}
   * @return:
   * @Description:获取本地存储的方法
   */
  public getItem(key: string) {
    key = this.getKey(key);
    const storeData: string | null = window.localStorage.getItem(key);
    if (storeData) {
      const {
        value,
        options: { storeTime },
      } = JSON.parse(storeData);
      // 如果从存储中获取的时间大于当前的时间或者等于0的时候表示当前的localStorage有效
      if (storeTime > new Date().getTime()) {
        return value;
      } else {
        this.removeItem(key);
        return null;
      }
    }
    return null;
  }

  

  /**
   * @param {type}
   * @return:
   */
  public setItem(key: string, value: string, time?: any) {
    key = this.getKey(key);
    // 如果用户没传递时间进来就是一天
    try {
      time = new Date(time).getTime() || time.getTime();
    } catch (e) {
      time = new Date().getTime() + 1000 * 60 * 60 * 24 * 1;
    }
    const options: { [propsName: string]: any } = {
      storeTime: time,
      prefix: this.prefix,
    };
    window.localStorage.setItem(key, JSON.stringify({ value, options }));
  }

  

  /**
   * @param {type}
   * @return:
   * @Description: 删除存储
   */
  public removeItem(key: string): void {
    key = this.getKey(key);
    const value: string | null = this.getItem(key);
    if (value) {
      window.localStorage.removeItem(key);
    }
  }

  

posted @ 2020-01-19 10:24  龙旋风  阅读(847)  评论(1)    收藏  举报