Browse Source

仓储台账列表设置缓存

zhangqing 1 year ago
parent
commit
29c97db92a

+ 214 - 0
src/mixins/tableColumnsMixin.js

@@ -0,0 +1,214 @@
+import request from '@/utils/request';
+
+export default {
+  data() {
+    return {
+      newColumns: []
+    };
+  },
+  created() {
+    //从服务器获取缓存列表配置
+    this.getTabColumns();
+    // 创建防抖函数并绑定this
+    this.debouncedHandleColumnChange = this.debounce(
+      this.handleColumnChangeImpl,
+      1000
+    );
+  },
+  methods: {
+    // 实际的列变更处理逻辑
+    handleColumnChangeImpl() {
+      try {
+        const list = this.getStorage(this.cacheKeyUrl + 'Cols');
+        if (list) {
+          this.saveColumns(list);
+        }
+      } catch (error) {
+        console.error('处理列配置出错:', error);
+      }
+    },
+
+    // 列表变化回调
+    handleColumnChange() {
+      this.debouncedHandleColumnChange();
+    },
+
+    // 获取table-column配置
+    async getTabColumns(key) {
+      this.cacheKeyUrl = key || this.cacheKeyUrl;
+      const res = await this.getByTableId(this.cacheKeyUrl);
+      if (res?.columnConfig?.length > 0) {
+        //对比接口返回和本地columns
+        let { nlist, type } = this.columnsContrast(res.columnConfig);
+        //有更新则更新服务缓存配置
+        if (type) {
+          this.saveColumns(nlist);
+        }
+        this.setStorage(this.cacheKeyUrl + 'Cols', nlist);
+        // 更新列
+        if (this._computedWatchers && this._computedWatchers.columns) {
+          // console.log('columns 是计算属性');
+          this.columnsVersion++;
+        } else {
+          // console.log('columns 是 data 属性');
+          this.columns = [...this.columns];
+          this.newColumns = [...this.newColumns];
+        }
+      }
+    },
+    //服务器和本地配置columns对比
+    columnsContrast(list) {
+      const key = 'label';
+      var updateType = 0;
+      let sList = list.filter((d, i, r) => {
+        return d[key];
+      });
+      let devColumns =
+        this.newColumns?.length > 0 ? this.columns : this.newColumns;
+      let dList = devColumns.filter((d, i, r) => {
+        return d[key] && d[key] !== '序号';
+      });
+      //本地columns长度小于1则直接返回
+      if (devColumns.length <= 0) {
+        return { nlist: list, type: updateType };
+      }
+      const keysA = new Set(sList.map((item) => item[key]));
+      const keysB = new Set(dList.map((item) => item[key]));
+      // 本地 比 缓存服务端 多的对象(新增)
+      const added = dList.filter((item) => {
+        return !keysA.has(item[key]) && (item.prop || item.label === '操作');
+      });
+      // 本地 比 缓存服务端 少的对象(删除)
+      const removed = sList.filter((item) => !keysB.has(item[key]));
+      const removedPropSet = new Set(removed.map((item) => item[key]));
+      // 删除 缓存中 中被移除的对象
+      const keptA = list.filter((item) => !removedPropSet.has(item[key]));
+      added.forEach((item) => {
+        //新增columns字段prop参数为必填
+        if (item.prop) {
+          item.id = item.prop;
+        } else if (item.columnKey) {
+          item.id = item.columnKey;
+        }
+        item.checked = true;
+      });
+
+      if (added.length > 0 || removed.length > 0) {
+        updateType = 1;
+      }
+
+      // 更新项:key 存在但内容变化
+      const dMap = new Map(dList.map((item) => [item[key], item]));
+      const updated = keptA.map((sItem) => {
+        const dItem = dMap.get(sItem[key]);
+        if (dItem && dItem.prop && sItem.prop !== dItem.prop) {
+          updateType = 1;
+          // 记录旧值和新值
+          const oldValue = sItem.prop;
+          const newValue = dItem.prop;
+          // 遍历所有属性,动态替换匹配旧值的字段
+          const updatedItem = { ...sItem };
+          Object.keys(updatedItem).forEach((k) => {
+            if (updatedItem[k] === oldValue) {
+              updatedItem[k] = newValue;
+            }
+          });
+          return updatedItem;
+        }
+        return sItem;
+      });
+
+      // 合并保留的对象和新增的对象
+      return { nlist: [...updated, ...added], type: updateType };
+    },
+
+    // 提交columns配置
+    async saveColumns(e) {
+      const data = {
+        tableId: this.cacheKeyUrl,
+        columnConfig: e
+      };
+      const msg = await this.saveTableConfig(data);
+      // console.log('列配置保存成功:', msg);
+      return msg;
+    },
+
+    //获取localstorage缓存
+    setStorage(key, value) {
+      try {
+        localStorage.setItem(key, JSON.stringify(value));
+      } catch (e) {
+        console.log('LocalStorage 存储错误:', e);
+        if (e.name === 'QuotaExceededError') {
+          this.clearCacheByPrefix(); //缓存不足,清除
+          localStorage.setItem(key, JSON.stringify(value));
+        }
+      }
+    },
+
+    //缓存不足清除缓存
+    clearCacheByPrefix() {
+      const prefix = 'Cols'; // 标识后缀
+      Object.keys(localStorage).forEach((key) => {
+        if (key.endsWith(prefix)) {
+          localStorage.removeItem(key);
+          // console.log(`已清除缓存: ${key}`);
+        }
+      });
+      // console.log('缓存清除完成');
+    },
+
+    //设置localstorage缓存
+    getStorage(key) {
+      try {
+        const value = localStorage.getItem(key);
+        return value ? JSON.parse(value) : null;
+      } catch (e) {
+        console.error('LocalStorage 解析错误:', e);
+        return null;
+      }
+    },
+
+    //防抖函数
+    debounce(fn, delay) {
+      let timer = null;
+      return (...args) => {
+        clearTimeout(timer);
+        timer = setTimeout(() => {
+          fn.apply(this, args);
+        }, delay);
+      };
+    },
+
+    //获取column记录接口
+    async getByTableId(key) {
+      try {
+        const res = await request.get(
+          `/sys/table-config/getByTableId/${key}`,
+          {}
+        );
+        if (res.data.code == 0) {
+          return res.data.data;
+        }
+      } catch (error) {
+        console.error('获取列配置失败:', error);
+      }
+    },
+
+    // 添加column记录接口
+    async saveTableConfig(data) {
+      try {
+        const res = await request({
+          url: '/sys/table-config/save',
+          method: 'post',
+          data
+        });
+        if (res.data.code == 0) {
+          return res.data.data;
+        }
+      } catch (error) {
+        console.error('保存列配置失败:', error);
+      }
+    }
+  }
+};

+ 14 - 2
src/views/warehouseManagement/stockLedger/components/item-list.vue

@@ -4,7 +4,7 @@
     <item-search @search="reload" ref="refSeavch" :type="type" @handledime="handledime"></item-search>
     <ele-pro-table ref="table" class="table" :columns="columns" :datasource="datasource" height="calc(100vh - 325px)"
       full-height="calc(100vh - 116px)" tool-class="ele-toolbar-form" :pageSize="20" @select="selectChange"
-      @select-all="changeSelectAll">
+      @select-all="changeSelectAll" @columns-change="handleColumnChange" :cache-key="cacheKeyUrl">
       <!-- 表头工具栏 -->
       <template v-slot:toolbar="{ row }">
         <el-button v-if="selectedDime == 3" size="small" :disabled="checkRadioData.length == 0" icon="el-icon-set-up"
@@ -114,12 +114,14 @@ import {
 import barCode from '@/api/main/barCode';
 import storageApi from '@/api/warehouseManagement';
 import { getBatchDetails } from '@/api/classifyManage/index';
+import tabMixins from '@/mixins/tableColumnsMixin';
 
 import {
   qualityStatus, qualityResults
 } from '@/utils/dict/index';
 
 export default {
+  mixins: [tabMixins],
   components: { ItemSearch, print, allot },
   props: {
     // 机构id
@@ -146,7 +148,11 @@ export default {
       searchForm: {
         dimension: '1'
       },
-      selectedDime: '1'
+      selectedDime: '1',
+      
+      diffCacheKeyUrl: 'eos-439decaa-warehouseManagement-stockLedger-products',
+      cacheKeyUrl: 'eos-439decaa-warehouseManagement-stockLedger-products1', //默认查询key值
+      columnsVersion: 1,
     };
   },
   created() {
@@ -155,6 +161,8 @@ export default {
   computed: {
     // 表格列配置
     columns() {
+      // 当columnsVersion变化时会重新计算
+      const version = this.columnsVersion;
       // selectedDime 1物品维度 2批次维度 3包装维度 4物料维度
       let arr = [
         this.selectedDime == 3
@@ -501,6 +509,10 @@ export default {
       console.log(val, 'val');
       this.selectedDime = val;
       this.reload();
+
+      //每次切换维度查询列表配置信息,固定列配置  val 1 为物品维度,2 为批次维度,3 为包装维度。如果val值发生变化。请适配之前的维度 
+      this.cacheKeyUrl = this.diffCacheKeyUrl + val
+      this.getTabColumns()
     },
     /* 表格数据源 */
     datasource({ page, limit, where, order }) {

+ 11 - 1
src/views/warehouseManagement/stockLedger/index.vue

@@ -79,7 +79,8 @@
         },
         currentId: '',
         treeList: [],
-        treeLoading: false
+        treeLoading: false,
+        cacheKeyUrl: 'eos-439decaa-warehouseManagement-stockLedger-products1'
       };
     },
     async created() {
@@ -89,6 +90,15 @@
       tabsChange(val) {
         this.currentTab = val;
         this.getTreeData();
+        
+        // //切换左侧维度,获取服务列表配置
+        if (val === 'products') {
+          this.cacheKeyUrl= "eos-439decaa-warehouseManagement-stockLedger-products1"
+        } else if (val === 'warehouse') {
+          this.cacheKeyUrl= "eos-439decaa-warehouseManagement-stockLedger-warehouse"
+        }
+
+        this.$refs.listRef.getTabColumns(this.cacheKeyUrl)
       },
       async getTreeData() {
         try {