tableColumnsMixin.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import request from '@/utils/request';
  2. export default {
  3. data() {
  4. return {
  5. newColumns: []
  6. };
  7. },
  8. created() {
  9. //从服务器获取缓存列表配置
  10. this.getTabColumns();
  11. // 创建防抖函数并绑定this
  12. this.debouncedHandleColumnChange = this.debounce(
  13. this.handleColumnChangeImpl,
  14. 1000
  15. );
  16. },
  17. methods: {
  18. // 实际的列变更处理逻辑
  19. handleColumnChangeImpl() {
  20. try {
  21. const list = this.getStorage(this.cacheKeyUrl + 'Cols');
  22. if (list) {
  23. this.saveColumns(list);
  24. }
  25. } catch (error) {
  26. console.error('处理列配置出错:', error);
  27. }
  28. },
  29. // 列表变化回调
  30. handleColumnChange() {
  31. this.debouncedHandleColumnChange();
  32. },
  33. // 获取table-column配置
  34. async getTabColumns() {
  35. const res = await this.getByTableId(this.cacheKeyUrl);
  36. if (res?.columnConfig?.length > 0) {
  37. //对比接口返回和本地columns
  38. let { nlist, type } = this.columnsContrast(res.columnConfig);
  39. //有更新则更新服务缓存配置
  40. if (type) {
  41. this.saveColumns(nlist);
  42. }
  43. this.setStorage(this.cacheKeyUrl + 'Cols', nlist);
  44. // 更新列
  45. if (this._computedWatchers && this._computedWatchers.columns) {
  46. // console.log('columns 是计算属性');
  47. this.columnsVersion++;
  48. } else {
  49. // console.log('columns 是 data 属性');
  50. this.columns = [...this.columns];
  51. this.newColumns = [...this.newColumns];
  52. }
  53. }
  54. },
  55. //服务器和本地配置columns对比
  56. columnsContrast(list) {
  57. const key = 'label';
  58. var updateType = 0;
  59. let sList = list.filter((d, i, r) => {
  60. return d[key];
  61. });
  62. let devColumns =
  63. this.newColumns?.length > 0 ? this.newColumns : this.columns;
  64. let dList = devColumns.filter((d, i, r) => {
  65. return d[key] && d[key] !== '序号';
  66. });
  67. const keysA = new Set(sList.map((item) => item[key]));
  68. const keysB = new Set(dList.map((item) => item[key]));
  69. // 本地 比 缓存服务端 多的对象(新增)
  70. const added = dList.filter((item) => {
  71. return !keysA.has(item[key]) && (item.prop || item.label === '操作');
  72. });
  73. // 本地 比 缓存服务端 少的对象(删除)
  74. const removed = sList.filter((item) => !keysB.has(item[key]));
  75. const removedPropSet = new Set(removed.map((item) => item[key]));
  76. // 删除 缓存中 中被移除的对象
  77. const keptA = list.filter((item) => !removedPropSet.has(item[key]));
  78. added.forEach((item) => {
  79. //新增columns字段prop参数为必填
  80. if (item.prop) {
  81. item.id = item.prop;
  82. } else if (item.columnKey) {
  83. item.id = item.columnKey;
  84. }
  85. item.checked = true;
  86. });
  87. if (added.length > 0 || removed.length > 0) {
  88. updateType = 1;
  89. }
  90. // 更新项:key 存在但内容变化
  91. const dMap = new Map(dList.map((item) => [item[key], item]));
  92. const updated = keptA.map((sItem) => {
  93. const dItem = dMap.get(sItem[key]);
  94. if (dItem && dItem.prop && sItem.prop !== dItem.prop) {
  95. updateType = 1;
  96. // 记录旧值和新值
  97. const oldValue = sItem.prop;
  98. const newValue = dItem.prop;
  99. // 遍历所有属性,动态替换匹配旧值的字段
  100. const updatedItem = { ...sItem };
  101. Object.keys(updatedItem).forEach((k) => {
  102. if (updatedItem[k] === oldValue) {
  103. updatedItem[k] = newValue;
  104. }
  105. });
  106. return updatedItem;
  107. }
  108. return sItem;
  109. });
  110. // 合并保留的对象和新增的对象
  111. return { nlist: [...updated, ...added], type: updateType };
  112. },
  113. // 提交columns配置
  114. async saveColumns(e) {
  115. const data = {
  116. tableId: this.cacheKeyUrl,
  117. columnConfig: e
  118. };
  119. const msg = await this.saveTableConfig(data);
  120. // console.log('列配置保存成功:', msg);
  121. return msg;
  122. },
  123. //获取localstorage缓存
  124. setStorage(key, value) {
  125. try {
  126. localStorage.setItem(key, JSON.stringify(value));
  127. } catch (e) {
  128. console.log('LocalStorage 存储错误:', e);
  129. if (e.name === 'QuotaExceededError') {
  130. this.clearCacheByPrefix(); //缓存不足,清除
  131. localStorage.setItem(key, JSON.stringify(value));
  132. }
  133. }
  134. },
  135. //缓存不足清除缓存
  136. clearCacheByPrefix() {
  137. const prefix = 'Cols'; // 标识后缀
  138. Object.keys(localStorage).forEach((key) => {
  139. if (key.endsWith(prefix)) {
  140. localStorage.removeItem(key);
  141. // console.log(`已清除缓存: ${key}`);
  142. }
  143. });
  144. // console.log('缓存清除完成');
  145. },
  146. //设置localstorage缓存
  147. getStorage(key) {
  148. try {
  149. const value = localStorage.getItem(key);
  150. return value ? JSON.parse(value) : null;
  151. } catch (e) {
  152. console.error('LocalStorage 解析错误:', e);
  153. return null;
  154. }
  155. },
  156. //防抖函数
  157. debounce(fn, delay) {
  158. let timer = null;
  159. return (...args) => {
  160. clearTimeout(timer);
  161. timer = setTimeout(() => {
  162. fn.apply(this, args);
  163. }, delay);
  164. };
  165. },
  166. //获取column记录接口
  167. async getByTableId(key) {
  168. try {
  169. const res = await request.get(
  170. `/sys/table-config/getByTableId/${key}`,
  171. {}
  172. );
  173. if (res.data.code == 0) {
  174. return res.data.data;
  175. }
  176. } catch (error) {
  177. console.error('获取列配置失败:', error);
  178. }
  179. },
  180. // 添加column记录接口
  181. async saveTableConfig(data) {
  182. try {
  183. const res = await request({
  184. url: '/sys/table-config/save',
  185. method: 'post',
  186. data
  187. });
  188. if (res.data.code == 0) {
  189. return res.data.data;
  190. }
  191. } catch (error) {
  192. console.error('保存列配置失败:', error);
  193. }
  194. }
  195. }
  196. };