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