/*
 * @Description: 页面跳转时保存当前浏览位置和数据，返回时加载原有数据
 * @Date: 2020-11-19 11:49:00
 * @LastEditors: gzw
 * @LastEditTime: 2020-11-19 14:46:51
 */
export default {
  data() {
    return {
      cacheKey: '',
      saveKeys: [],
      loadCache: false
    };
  },
  methods: {
    setListCache() {
      const val = {};
      if (!this.saveKeys || !this.saveKeys.length) return;
      this.saveKeys.forEach(item => {
        val[item] = this[item];
      });
      val.scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      sessionStorage.setItem(this.cacheKey, JSON.stringify(val));
    },
    clearListCache() {
      sessionStorage.removeItem(this.cacheKey);
    },
    hasListCache() {
      return !!sessionStorage.getItem(this.cacheKey);
    },
    getListCache() {
      this.loadCache = true;
      const listCache = JSON.parse(sessionStorage.getItem(this.cacheKey));
      this.saveKeys.forEach(item => {
        this[item] = listCache[item];
      });
      document.documentElement.scrollTop = listCache.scrollTop;
      document.body.scrollTop = listCache.scrollTop;
      this.clearListCache();
      this.$nextTick(() => {
        this.loadCache = false;
      });
    }
  }
};
