ListStateMixin.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /**
  2. * 列表页状态保持 Mixin v2(安全模式)
  3. *
  4. * 核心能力(零风险):
  5. * 1. keep-alive 缓存 + activated() 自动刷新(探测 loader)——解决「编辑返回状态丢失」的核心痛点
  6. * 2. 可选:URL query 同步/还原 —— 仅当页面显式声明 listStateMap 时启用,防止形态差异导致误伤
  7. *
  8. * 页面接入(两种模式任选其一):
  9. * A. 仅保状态(默认):mixins: [ListStateMixin],其它不用动。
  10. * B. 额外要 URL 深链:在组件选项声明 listStateMap(见下),并确保 loader 名称在 LOADER_CANDIDATES 中。
  11. *
  12. * listStateMap 说明:
  13. * - filters: 'searchForm' | ['keyword','type'] | null 筛选字段来源
  14. * - pagination: { page: 'pagination.current', size: 'pagination.size' } | { page: 'page', size: 'size' } | { page: 'currentPage', size: 'pageSize' } | { page: 'pageNum', size: 'pageSize' } | { page: 'filter.page', size: 'filter.size' } // 点路径
  15. * - loader: 'loadChildren' | 'loadData' | 'loadActivities' | 'loadList' | ... 若不在候选名单需显式指定
  16. * - combined?: true // 分页键在 filters 对象内(如 filter.page, query.page),此时分页路径相对 filters 对象
  17. *
  18. * 常见预设(可直接用):
  19. * // searchForm + pagination.current/size
  20. * listStateMap: { filters: 'searchForm', pagination: { page: 'pagination.current', size: 'pagination.size' }, loader: 'loadXxx' }
  21. *
  22. * // filter 内含 page/size + 独立 keyword
  23. * listStateMap: { filters: 'filter', pagination: { page: 'page', size: 'size' }, loader: 'loadXxx', combined: true }
  24. *
  25. * // query 对象包含 page/pageSize
  26. * listStateMap: { filters: 'query', pagination: { page: 'page', size: 'pageSize' }, loader: 'loadXxx', combined: true }
  27. *
  28. * // 仅独立 page/size(无筛选对象)
  29. * listStateMap: { filters: null, pagination: { page: 'page', size: 'size' }, loader: 'loadXxx' }
  30. *
  31. * 重置:页面「重置」按钮处调用 this.resetListState()(需已声明 map)。
  32. */
  33. import { sameQuery, ALLOWED_PAGE_SIZES } from '@/utils/listState'
  34. // 常见加载方法名(自动探测顺序;也可在 map 中显式指定 loader)
  35. const LOADER_CANDIDATES = [
  36. 'loadList', 'loadData', 'loadActivities', 'loadChildren', 'loadFamilies', 'loadUsers',
  37. 'loadRewards', 'loadWishes', 'loadPointsLogs', 'loadTasks', 'loadChildTasks', 'loadTemplates',
  38. 'fetchLogs', 'loadPackages', 'loadSummary', 'loadLogs', 'loadProducts', 'loadOrders',
  39. 'loadAssignments', 'loadTemplates'
  40. ]
  41. // 常见筛选对象名(仅用于自动 loader 探测,不做 URL sync)
  42. const FILTER_OBJECT_CANDIDATES = [
  43. 'filters', 'searchForm', 'filter', 'query', 'listQuery', 'filterForm', 'recordFilter', 'searchParams'
  44. ]
  45. // 常见分页字段名(仅用于自动探测辅助)
  46. const PAGE_KEYS = ['page', 'current', 'pageNo', 'pageNum', 'currentPage']
  47. const SIZE_KEYS = ['size', 'pageSize', 'pageLimit', 'limit']
  48. function getByPath(obj, path) {
  49. if (!obj || !path) return undefined
  50. return path.split('.').reduce((o, k) => (o && o[k] !== undefined ? o[k] : undefined), obj)
  51. }
  52. function setByPath(obj, path, val) {
  53. if (!obj || !path) return
  54. const keys = path.split('.')
  55. const last = keys.pop()
  56. const target = keys.reduce((o, k) => (o && o[k] !== undefined ? o[k] : undefined), obj)
  57. if (target) target[last] = val
  58. }
  59. export default {
  60. created() {
  61. // 1) 读取显式 map(优先)或为 undefined(不启用 URL 同步)
  62. this._lsMap = this.$options.listStateMap || null
  63. // 2) 自动探测 loader(用于 activated 刷新)——不依赖 map,保证最小功能可用
  64. this._lsLoaderName = LOADER_CANDIDATES.find(k => typeof this[k] === 'function')
  65. // 3) 若有 map,做快照(用于 reset)并包装 loader 以便 URL 同步
  66. if (this._lsMap) {
  67. this._lsSnapshot()
  68. this._lsWrapLoader()
  69. this.restoreStateFromUrl()
  70. }
  71. },
  72. activated() {
  73. // keep-alive 返回时刷新列表(无 map 也生效,只依赖 loader)
  74. if (this._lsActivated) this.reloadKeepingState()
  75. this._lsActivated = true
  76. this.$nextTick(() => {
  77. if (this.$refs.table && typeof this.$refs.table.doLayout === 'function') {
  78. this.$refs.table.doLayout()
  79. }
  80. })
  81. },
  82. methods: {
  83. // === URL 同步/还原(仅在 _lsMap 存在时有效) ===
  84. restoreStateFromUrl() {
  85. if (!this._lsMap) return
  86. const q = this.$route && this.$route.query ? this.$route.query : {}
  87. const m = this._lsMap
  88. // filters
  89. if (m.filters) {
  90. const src = typeof m.filters === 'string' ? this[m.filters] : null
  91. if (src) {
  92. if (Array.isArray(m.filters)) {
  93. m.filters.forEach(k => { if (q[k] !== undefined) this[k] = q[k] })
  94. } else {
  95. Object.keys(src).forEach(k => {
  96. if (k === 'sort' || k === 'total') return
  97. if (PAGE_KEYS.includes(k) || SIZE_KEYS.includes(k)) return
  98. if (q[k] !== undefined && q[k] !== '' && q[k] !== null) {
  99. src[k] = q[k]
  100. }
  101. })
  102. }
  103. }
  104. }
  105. // pagination
  106. if (m.pagination) {
  107. const pageVal = q.page ? parseInt(q.page, 10) : NaN
  108. const sizeVal = q.size ? parseInt(q.size, 10) : NaN
  109. if (m.combined && m.filters && typeof m.filters === 'string') {
  110. const filterObj = this[m.filters]
  111. if (m.pagination.page) setByPath(filterObj, m.pagination.page, pageVal)
  112. if (m.pagination.size && !isNaN(sizeVal) && ALLOWED_PAGE_SIZES.includes(sizeVal)) setByPath(filterObj, m.pagination.size, sizeVal)
  113. } else {
  114. if (m.pagination.page && !isNaN(pageVal) && pageVal > 0) setByPath(this, m.pagination.page, pageVal)
  115. if (m.pagination.size && !isNaN(sizeVal) && ALLOWED_PAGE_SIZES.includes(sizeVal)) setByPath(this, m.pagination.size, sizeVal)
  116. }
  117. }
  118. // sort
  119. if (this.sortState && q.sort) {
  120. const s = []
  121. q.sort.split(',').forEach(pair => {
  122. const i = pair.indexOf(':')
  123. if (i > 0) {
  124. const col = pair.slice(0, i), ord = pair.slice(i + 1)
  125. if (ord === 'asc' || ord === 'desc') s.push({ column: col, order: ord })
  126. }
  127. })
  128. this.sortState = s
  129. }
  130. },
  131. syncStateToUrl() {
  132. if (!this._lsMap || !this.$route || !this.$router) return
  133. const m = this._lsMap
  134. const next = {}
  135. // filters
  136. if (m.filters) {
  137. const src = typeof m.filters === 'string' ? this[m.filters] : null
  138. if (src) {
  139. if (Array.isArray(m.filters)) {
  140. m.filters.forEach(k => {
  141. const v = this[k]
  142. if (v !== undefined && v !== null && v !== '' && typeof v !== 'object') next[k] = String(v)
  143. })
  144. } else {
  145. Object.keys(src).forEach(k => {
  146. if (k === 'sort' || k === 'total') return
  147. if (PAGE_KEYS.includes(k) || SIZE_KEYS.includes(k)) return
  148. const v = src[k]
  149. if (v !== undefined && v !== null && v !== '' && typeof v !== 'object') next[k] = String(v)
  150. })
  151. }
  152. }
  153. }
  154. // pagination
  155. if (m.pagination) {
  156. let pageVal, sizeVal
  157. if (m.combined && m.filters && typeof m.filters === 'string') {
  158. const filterObj = this[m.filters]
  159. pageVal = getByPath(filterObj, m.pagination.page)
  160. sizeVal = getByPath(filterObj, m.pagination.size)
  161. } else {
  162. pageVal = getByPath(this, m.pagination.page)
  163. sizeVal = getByPath(this, m.pagination.size)
  164. }
  165. if (pageVal && pageVal > 1) next.page = String(pageVal)
  166. if (sizeVal && sizeVal !== (this._lsDefaultSize || 20)) next.size = String(sizeVal)
  167. }
  168. // sort
  169. if (this.sortState && this.sortState.length) {
  170. next.sort = this.sortState.map(s => s.column + ':' + s.order).join(',')
  171. }
  172. const curQuery = this.$route && this.$route.query ? this.$route.query : {}
  173. if (sameQuery(next, curQuery)) return
  174. this.$router.replace({ path: this.$route.path, query: next }).catch(() => {})
  175. },
  176. resetListState() {
  177. if (!this._lsMap) return
  178. const m = this._lsMap
  179. if (m.filters) {
  180. const src = typeof m.filters === 'string' ? this[m.filters] : null
  181. if (src && this._lsDefaultFilters) {
  182. if (Array.isArray(m.filters)) {
  183. m.filters.forEach(k => { if (this._lsDefaultLoose && this._lsDefaultLoose[k] !== undefined) this[k] = this._lsDefaultLoose[k] })
  184. } else {
  185. Object.keys(src).forEach(k => { if (this._lsDefaultFilters[k] !== undefined) src[k] = this._lsDefaultFilters[k] })
  186. }
  187. }
  188. }
  189. if (m.pagination) {
  190. if (m.combined && m.filters && typeof m.filters === 'string') {
  191. const filterObj = this[m.filters]
  192. if (m.pagination.page) setByPath(filterObj, m.pagination.page, 1)
  193. if (m.pagination.size && this._lsDefaultSize) setByPath(filterObj, m.pagination.size, this._lsDefaultSize)
  194. } else {
  195. if (m.pagination.page) setByPath(this, m.pagination.page, 1)
  196. if (m.pagination.size && this._lsDefaultSize) setByPath(this, m.pagination.size, this._lsDefaultSize)
  197. }
  198. }
  199. if (this.sortState) this.sortState = []
  200. },
  201. // === activated 刷新(无 map 也生效) ===
  202. reloadKeepingState() {
  203. const name = this._lsLoaderName
  204. if (name && typeof this[name] === 'function') {
  205. this[name]()
  206. } else {
  207. // 兜底:遍历候选列表
  208. for (const k of LOADER_CANDIDATES) {
  209. if (typeof this[k] === 'function') { this[k](); break }
  210. }
  211. }
  212. },
  213. // 内部方法
  214. _lsSnapshot() {
  215. const m = this._lsMap
  216. if (!m) return
  217. if (m.filters) {
  218. const src = typeof m.filters === 'string' ? this[m.filters] : null
  219. if (src) {
  220. if (Array.isArray(m.filters)) {
  221. this._lsDefaultLoose = {}
  222. m.filters.forEach(k => { this._lsDefaultLoose[k] = this[k] })
  223. } else {
  224. this._lsDefaultFilters = {}
  225. Object.keys(src).forEach(k => { this._lsDefaultFilters[k] = src[k] })
  226. }
  227. }
  228. }
  229. if (m.pagination && m.pagination.size) {
  230. if (m.combined && m.filters && typeof m.filters === 'string') {
  231. const filterObj = this[m.filters]
  232. this._lsDefaultSize = getByPath(filterObj, m.pagination.size)
  233. } else {
  234. this._lsDefaultSize = getByPath(this, m.pagination.size)
  235. }
  236. }
  237. },
  238. _lsWrapLoader() {
  239. const name = this._lsLoaderName
  240. if (!name) return
  241. const orig = this[name]
  242. if (typeof orig !== 'function') return
  243. const self = this
  244. this[name] = async function(...args) {
  245. const r = await orig.apply(this, args)
  246. self.syncStateToUrl()
  247. return r
  248. }
  249. }
  250. }
  251. }