tableColumnsMixin.js 6.4 KB

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