el-table 自定义列宽并缓存插件

使用方式

在main.ts中引入并注册插件:

import TableColumnCache from './plugins/tablekey/tableColumnCache'

const setupAll = async () => {

  const app = createApp(App)

  app.use(TableColumnCache)

}


插件代码(tableColumnCache.ts)

import { App, nextTick } from 'vue'

export default {

  install(app: App) {

    app.mixin({

      mounted() {

        const el = (this as any).$el as any

        if (!el?.classList?.contains('el-table')) return

        const tableVm = el.__vueParentComponent?.proxy

        if (!tableVm?.store?.states?.columns?.value) return

        const pageKey = window.location.pathname

        // 获取当前页面该表格在页面中的索引,保证多表格互不覆盖

        const tableList = document.querySelectorAll('.el-table')

        const tableIndex = Array.from(tableList).indexOf(el)

        const tableKey = pageKey + '_' + (el.id || `table_${tableIndex}`)

        // 1️⃣ 恢复缓存列宽

        nextTick(() => {

          const saved = JSON.parse(localStorage.getItem('table_column_width') || '{}')

          const tableSaved = saved[tableKey] || {}

          tableVm.store.states.columns.value.forEach((col: any, index: number) => {

            const colId = (col.property || col.label) + '_' + index

            const width = tableSaved[colId]

            if (width !== undefined) {

              col.width = width

              col.realWidth = width

            }

          })

          tableVm.doLayout()

        })

        // 2️⃣ 拦截 header-dragend 保存缓存

        const origEmit = tableVm.$.emit

        tableVm.$.emit = new Proxy(origEmit, {

          apply(target, thisArg, args) {

            if (args[0] === 'header-dragend') {

              const [newWidth, , column] = args.slice(1)

              const saved = JSON.parse(localStorage.getItem('table_column_width') || '{}')

              if (!saved[tableKey]) saved[tableKey] = {}

              // 生成唯一 key

              const colIndex = tableVm.store.states.columns.value.indexOf(column)

              const colId = (column.property || column.label) + '_' + colIndex

              saved[tableKey][colId] = newWidth

              localStorage.setItem('table_column_width', JSON.stringify(saved))

            }

            return Reflect.apply(target, thisArg, args)

          }

        })

      }

    })

  }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容