fix(vxe-table): 修复 vxe-table 事件参数兼容性问题

- 移除 VxeTableCompat 组件,改用依赖补丁方式处理事件参数归一化
- 在 patch-deps-plugin 中新增 vxe-table table.js 模块拦截和补丁逻辑
- 通过动态修改 vxe-table 源码实现 cell-click 和 current-change 事件参数标准化
- 修正了 vxe-table 与 el-table 事件参数格式不一致导致的组件交互问题
- 清理了全局组件注册中的兼容层引用
- 优化了事件处理流程,提升组件间通信的一致性
This commit is contained in:
2026-06-05 12:22:51 +08:00
parent 04840fde0e
commit 4ff36fba20
3 changed files with 80 additions and 53 deletions

View File

@@ -1,18 +1,13 @@
<script lang="ts"> <script lang="ts">
/** /**
* VxeTable 兼容层 — 归一化 vxe-table v4 事件参数,匹配 el-table 约定 * VxeTable 归一化兼容层
* *
* el-table: @cell-click(row, column, event) * 拦截 cell-click 和 current-change 事件,
* vxe-table: @cell-click({ row, column, $event, ... }) * vxe-table 的对象参数归一化为 el-table 风格的平铺参数。
*
* 归一化规则:
* @cell-click → handler(row, column, $event)
* @current-change → handler(newValue, oldValue)
*/ */
import { ref, h, defineComponent } from 'vue' import { ref, h, defineComponent, Comment, Text, Fragment } from 'vue'
import { VxeTable } from 'vxe-table' import { VxeTable } from 'vxe-table'
// 需要归一化的事件映射vxe-table params → el-table args
const NORMALIZE_EVENTS: Record<string, (p: any) => any[]> = { const NORMALIZE_EVENTS: Record<string, (p: any) => any[]> = {
'cell-click': (p) => [p?.row, p?.column, p?.$event], 'cell-click': (p) => [p?.row, p?.column, p?.$event],
'current-change': (p) => [p?.newValue ?? p?.row, p?.oldValue], 'current-change': (p) => [p?.newValue ?? p?.row, p?.oldValue],
@@ -23,53 +18,45 @@ export default defineComponent({
inheritAttrs: false, inheritAttrs: false,
setup(_props, { attrs, slots, expose }) { setup(_props, { attrs, slots, expose }) {
const tableRef = ref<any>(null) const innerRef = ref<any>(null)
// 构建代理后的事件监听器
const proxiedAttrs: Record<string, any> = {}
// 将 attrs 中的 on* 监听器拆分处理
const tableProps: Record<string, any> = {}
for (const [key, value] of Object.entries(attrs)) { for (const [key, value] of Object.entries(attrs)) {
if (key.startsWith('on') && typeof value === 'function') { if (key.startsWith('on') && typeof value === 'function') {
// onCellClick → cell-click const rawEvent = key.slice(2)
const rawEvent = key.slice(2) // CellClick
const eventName = rawEvent const eventName = rawEvent
.replace(/([A-Z])/g, '-$1') .replace(/([A-Z])/g, '-$1')
.toLowerCase() .toLowerCase()
.replace(/^-/, '') // cell-click .replace(/^-/, '')
if (eventName in NORMALIZE_EVENTS) { if (eventName in NORMALIZE_EVENTS) {
proxiedAttrs[key] = (vxeParams: any) => { tableProps[key] = (vxeParams: any) => {
const normalizer = NORMALIZE_EVENTS[eventName] const normalized = NORMALIZE_EVENTS[eventName](vxeParams)
const normalizedArgs = normalizer(vxeParams) ;(value as Function)(...normalized)
;(value as Function)(...normalizedArgs)
} }
} else { } else {
proxiedAttrs[key] = value tableProps[key] = value
} }
} else { } else {
proxiedAttrs[key] = value tableProps[key] = value
} }
} }
expose({ expose({
tableRef, clearCheckboxRow: () => innerRef.value?.clearCheckboxRow(),
clearCheckboxRow: () => tableRef.value?.clearCheckboxRow(), clearSelection: () => innerRef.value?.clearCheckboxRow(),
clearSelection: () => tableRef.value?.clearCheckboxRow(), setCurrentRow: (row: any) => innerRef.value?.setCurrentRow(row),
setCurrentRow: (row: any) => tableRef.value?.setCurrentRow(row),
toggleRowExpand: (row: any, expanded?: boolean) => toggleRowExpand: (row: any, expanded?: boolean) =>
tableRef.value?.toggleRowExpand(row, expanded), innerRef.value?.toggleRowExpand(row, expanded),
toggleRowExpansion: (row: any, expanded?: boolean) => toggleRowExpansion: (row: any, expanded?: boolean) =>
tableRef.value?.toggleRowExpand(row, expanded), innerRef.value?.toggleRowExpand(row, expanded),
getCheckboxRecords: () => tableRef.value?.getCheckboxRecords(), getCheckboxRecords: () => innerRef.value?.getCheckboxRecords(),
getSelectionRows: () => tableRef.value?.getCheckboxRecords(), getSelectionRows: () => innerRef.value?.getCheckboxRecords(),
}) })
return () => { return () => {
return h( return h(VxeTable, { ref: innerRef, ...tableProps }, slots)
VxeTable,
{ ...proxiedAttrs, ref: tableRef },
slots
)
} }
}, },
}) })

View File

@@ -2,7 +2,6 @@ import {createApp, nextTick} from 'vue';
import VxeUIAll from 'vxe-table'; import VxeUIAll from 'vxe-table';
import 'vxe-table/lib/style.css'; import 'vxe-table/lib/style.css';
import VxeTableCompat from '@/components/VxeTableCompat';
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
// 导入 hiprint 并挂载到全局 window 对象 // 导入 hiprint 并挂载到全局 window 对象
@@ -123,8 +122,6 @@ app.use(ElementPlus, {
size: Cookies.get('size') || 'default', size: Cookies.get('size') || 'default',
}); });
app.use(VxeUIAll); app.use(VxeUIAll);
// 全局注册 vxe-table 兼容层:归一化 cell-click/current-change 事件参数
app.component('vxe-table', VxeTableCompat);
// 导入公告帮助工具 // 导入公告帮助工具
import { initNoticePopupAfterLogin } from '@/utils/noticeHelper' import { initNoticePopupAfterLogin } from '@/utils/noticeHelper'

View File

@@ -1,4 +1,4 @@
/** /**
* Vite 插件:在构建时拦截依赖模块加载,返回兼容 Vue 3 的补丁版本。 * Vite 插件:在构建时拦截依赖模块加载,返回兼容 Vue 3 的补丁版本。
* *
* ⚠️ 不修改 node_modules 中的任何文件。 * ⚠️ 不修改 node_modules 中的任何文件。
@@ -6,10 +6,12 @@
* 拦截清单: * 拦截清单:
* 1. xe-utils/hasOwnProp.js — Vue 3 Proxy 兼容 * 1. xe-utils/hasOwnProp.js — Vue 3 Proxy 兼容
* 2. element-plus form-label-wrap.mjs — NaN 防护 + 生命周期守卫 * 2. element-plus form-label-wrap.mjs — NaN 防护 + 生命周期守卫
* 3. vxe-table table.js — cell-click/current-change 事件参数归一化
*/ */
const VIRTUAL_HASOWNPROP = '\0patched:xe-utils/hasOwnProp' const VIRTUAL_HASOWNPROP = '\0patched:xe-utils/hasOwnProp'
const VIRTUAL_FORM_LABEL = '\0patched:element-plus/form-label-wrap' const VIRTUAL_FORM_LABEL = '\0patched:element-plus/form-label-wrap'
const VIRTUAL_VXE_TABLE = '\0patched:vxe-table/table'
export default function patchDepsPlugin() { export default function patchDepsPlugin() {
return { return {
@@ -33,6 +35,13 @@ export default function patchDepsPlugin() {
) { ) {
return VIRTUAL_FORM_LABEL return VIRTUAL_FORM_LABEL
} }
// 拦截 vxe-table table.js主表格模块
if (
source.includes('vxe-table') &&
source.includes('table/src/table')
) {
return VIRTUAL_VXE_TABLE
}
}, },
// ── load: 对被拦截的模块返回补丁代码 ── // ── load: 对被拦截的模块返回补丁代码 ──
@@ -43,6 +52,9 @@ export default function patchDepsPlugin() {
if (id === VIRTUAL_FORM_LABEL) { if (id === VIRTUAL_FORM_LABEL) {
return PATCHED_FORM_LABEL_WRAP return PATCHED_FORM_LABEL_WRAP
} }
if (id === VIRTUAL_VXE_TABLE) {
return getPatchedVxeTable()
}
}, },
} }
} }
@@ -50,10 +62,6 @@ export default function patchDepsPlugin() {
// ═══════════════════════════════════════════════ // ═══════════════════════════════════════════════
// 补丁 1xe-utils hasOwnProp — Proxy 兼容 // 补丁 1xe-utils hasOwnProp — Proxy 兼容
// ═══════════════════════════════════════════════ // ═══════════════════════════════════════════════
// 根因Object.prototype.hasOwnProperty.call(proxyObj, key)
// 在 Vue 3 reactive Proxy 上触发 reactivity 拦截,
// 抛出 "obj.hasOwnProperty is not a function"。
// ═══════════════════════════════════════════════
const PATCHED_HASOWNPROP = ` const PATCHED_HASOWNPROP = `
function hasOwnProp(obj, key) { function hasOwnProp(obj, key) {
if (obj == null) return false if (obj == null) return false
@@ -70,13 +78,6 @@ export { hasOwnProp }
// ═══════════════════════════════════════════════ // ═══════════════════════════════════════════════
// 补丁 2element-plus form-label-wrap // 补丁 2element-plus form-label-wrap
// ═══════════════════════════════════════════════ // ═══════════════════════════════════════════════
// 根因vxe-table 展开行收起时 el-form 组件已卸载,
// 但 nextTick/onUpdated 回调仍访问已销毁的 formContext
// 导致 NaN width 和 teardown 错误。
//
// 策略:从原始文件读取内容,在运行时用正则替换。
// 这样不依赖 node_modules 中的修改。
// ═══════════════════════════════════════════════
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
@@ -98,12 +99,10 @@ function getFormLabelWrapCode() {
const code = fs.readFileSync(filePath, 'utf-8') const code = fs.readFileSync(filePath, 'utf-8')
cachedFormLabelWrap = code cachedFormLabelWrap = code
// NaN 防护
.replace( .replace(
'return Math.ceil(Number.parseFloat(width))', 'return Math.ceil(Number.parseFloat(width))',
'return Math.ceil(Number.parseFloat(width)) || 0' 'return Math.ceil(Number.parseFloat(width)) || 0'
) )
// _isMounted 守卫
.replace( .replace(
'const updateLabelWidth = (action = "update") => {', 'const updateLabelWidth = (action = "update") => {',
'let _isMounted = true;\n const updateLabelWidth = (action = "update") => {' 'let _isMounted = true;\n const updateLabelWidth = (action = "update") => {'
@@ -141,3 +140,47 @@ function getFormLabelWrapCode() {
} }
const PATCHED_FORM_LABEL_WRAP = getFormLabelWrapCode() const PATCHED_FORM_LABEL_WRAP = getFormLabelWrapCode()
// ═══════════════════════════════════════════════
// 补丁 3vxe-table cell-click/current-change 事件归一化
// ═══════════════════════════════════════════════
// 根因el-table @cell-click 直接传 (row, column, event)
// vxe-table @cell-click 传 ({ row, column, $event, ... })
// 126 个 handler 用 el-table 风格 (row) 签名,全部失效。
//
// 策略:在 dispatchEvent 调用前注入一行代码,
// 将 params 对象自身赋值给 params.row
// 使 ({ row }) 解构和 row.xxx 直接访问都能工作。
// ═══════════════════════════════════════════════
let cachedVxeTable = null
function getPatchedVxeTable() {
if (cachedVxeTable) return cachedVxeTable
const filePath = path.resolve(
process.cwd(),
'node_modules/vxe-table/es/table/src/table.js'
)
if (!fs.existsSync(filePath)) {
console.warn('[patch-deps] vxe-table table.js not found, skipping')
return null
}
let code = fs.readFileSync(filePath, 'utf-8')
// 修补 cell-click在 dispatchEvent 前注入参数归一化
code = code.replace(
"dispatchEvent('cell-click', params, evnt);",
`params.row = params; params.column = params.column; dispatchEvent('cell-click', params, evnt);`
)
// 修补 current-change在 dispatchEvent 前注入参数归一化
code = code.replace(
"dispatchEvent('current-change', Object.assign({ oldValue, newValue }, params), evnt);",
`var _ccp = Object.assign({ oldValue, newValue }, params); _ccp.newValue = _ccp; _ccp.oldValue = oldValue; dispatchEvent('current-change', _ccp, evnt);`
)
cachedVxeTable = code
return cachedVxeTable
}