tableColumnsMixin.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. if (this.newColumns?.length) {
  64. devColumns = this.newColumns;
  65. }
  66. if (typeof this.columns == 'function') {
  67. devColumns = this.columns();
  68. } else {
  69. devColumns = this.columns;
  70. }
  71. let dList = devColumns.filter((d, i, r) => {
  72. return d[key] && d[key] !== '序号';
  73. });
  74. const keysA = new Set(sList.map((item) => item[key]));
  75. const keysB = new Set(dList.map((item) => item[key]));
  76. // 本地 比 缓存服务端 多的对象(新增)
  77. const added = dList.filter((item) => {
  78. return !keysA.has(item[key]) && (item.prop || item.label === '操作');
  79. });
  80. // 本地 比 缓存服务端 少的对象(删除)
  81. const removed = sList.filter((item) => !keysB.has(item[key]));
  82. const removedPropSet = new Set(removed.map((item) => item[key]));
  83. // 删除 缓存中 中被移除的对象
  84. const keptA = list.filter((item) => !removedPropSet.has(item[key]));
  85. added.forEach((item) => {
  86. //新增columns字段prop参数为必填
  87. if (item.prop) {
  88. item.id = item.prop;
  89. } else if (item.columnKey) {
  90. item.id = item.columnKey;
  91. }
  92. item.checked = true;
  93. });
  94. if (added.length > 0 || removed.length > 0) {
  95. updateType = 1;
  96. }
  97. // 更新项:key 存在但内容变化
  98. const dMap = new Map(dList.map((item) => [item[key], item]));
  99. const updated = keptA.map((sItem) => {
  100. const dItem = dMap.get(sItem[key]);
  101. if (dItem && dItem.prop && sItem.prop !== dItem.prop) {
  102. updateType = 1;
  103. // 记录旧值和新值
  104. const oldValue = sItem.prop;
  105. const newValue = dItem.prop;
  106. // 遍历所有属性,动态替换匹配旧值的字段
  107. const updatedItem = { ...sItem };
  108. Object.keys(updatedItem).forEach((k) => {
  109. if (updatedItem[k] === oldValue) {
  110. updatedItem[k] = newValue;
  111. }
  112. });
  113. return updatedItem;
  114. }
  115. return sItem;
  116. });
  117. // 合并保留的对象和新增的对象
  118. return { nlist: [...updated, ...added], type: updateType };
  119. },
  120. // 提交columns配置
  121. async saveColumns(e) {
  122. const data = {
  123. tableId: this.cacheKeyUrl,
  124. columnConfig: e
  125. };
  126. const msg = await this.saveTableConfig(data);
  127. // console.log('列配置保存成功:', msg);
  128. return msg;
  129. },
  130. //获取localstorage缓存
  131. setStorage(key, value) {
  132. try {
  133. localStorage.setItem(key, JSON.stringify(value));
  134. } catch (e) {
  135. console.log('LocalStorage 存储错误:', e);
  136. if (e.name === 'QuotaExceededError') {
  137. this.clearCacheByPrefix(); //缓存不足,清除
  138. localStorage.setItem(key, JSON.stringify(value));
  139. }
  140. }
  141. },
  142. //缓存不足清除缓存
  143. clearCacheByPrefix() {
  144. const prefix = 'Cols'; // 标识后缀
  145. Object.keys(localStorage).forEach((key) => {
  146. if (key.endsWith(prefix)) {
  147. localStorage.removeItem(key);
  148. // console.log(`已清除缓存: ${key}`);
  149. }
  150. });
  151. // console.log('缓存清除完成');
  152. },
  153. //设置localstorage缓存
  154. getStorage(key) {
  155. try {
  156. const value = localStorage.getItem(key);
  157. return value ? JSON.parse(value) : null;
  158. } catch (e) {
  159. console.error('LocalStorage 解析错误:', e);
  160. return null;
  161. }
  162. },
  163. //防抖函数
  164. debounce(fn, delay) {
  165. let timer = null;
  166. return (...args) => {
  167. clearTimeout(timer);
  168. timer = setTimeout(() => {
  169. fn.apply(this, args);
  170. }, delay);
  171. };
  172. },
  173. //获取column记录接口
  174. async getByTableId(key) {
  175. try {
  176. const res = await request.get(
  177. `/sys/table-config/getByTableId/${key}`,
  178. {}
  179. );
  180. if (res.data.code == 0) {
  181. return res.data.data;
  182. }
  183. } catch (error) {
  184. console.error('获取列配置失败:', error);
  185. }
  186. },
  187. // 添加column记录接口
  188. async saveTableConfig(data) {
  189. try {
  190. const res = await request({
  191. url: '/sys/table-config/save',
  192. method: 'post',
  193. data
  194. });
  195. if (res.data.code == 0) {
  196. return res.data.data;
  197. }
  198. } catch (error) {
  199. console.error('保存列配置失败:', error);
  200. }
  201. }
  202. }
  203. };