使用封装的 MyPagination 组件时,出现如下报错:
封装组件如下:
import { defineComponent } from 'vue';
import { ElConfigProvider, ElPagination, paginationProps } from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import './index.less';
export default defineComponent({
name: 'MyPagination',
props: paginationProps,
emits: [
"update:prevClick",
"update:nextClick",
"currentChange",
"update:sizeChange",
'update:currentPage',
'update:pageSize',
],
setup(props, {emit, attrs, slots }) {
const handleCurrentChange = (page) => {
emit('update:currentPage', page);
};
const handleSizeChange = (size) => {
emit('update:pageSize', size);
};
return () => (
<div class="my-pagination-root">
<ElConfigProvider namespace="ep" locale={zhCn}>
<div class={`business-pagination-common ${props.size ? `business-pagination-size-${props.size}` : ''}`}>
<ElPagination
{...props}
{...attrs}
onUpdate:current-page={(val) => emit('update:currentPage', val)}
onUpdate:page-size={(val) => emit('update:pageSize', val)}
onCurrent-change={handleCurrentChange}
onSize-change={handleSizeChange}
>
{/* 使用插槽,允许用户在此处插入自定义内容 */}
{slots.default ? slots.default() : null}
</ElPagination>
</div>
</ElConfigProvider>
</div>
);
},
});
使用如下:
<MyPagination
v-show={showPaging.value}
layout="total, sizes, prev, pager, next, jumper"
pageSizes={[20, 50, 100]}
v-model:pageSize={params.pageSize}
v-model:currentPage={params.pageIndex}
onSize-change={onSizeChange}
onCurrent-change={onCurrentChange}
total={totalCount.value}
/>
出现如下错误:
错误原因分析:
该警告 Runtime directive used on component with non-element root node 表示:父组件在某个子组件上使用了 Vue 指令(如 v-if、v-show、v-for),但该子组件的根节点(Root Node)不是原生 DOM 元素(例如是 Fragment 或多个根节点,或根节点是另一个组件如 <ElConfigProvider>)。Vue 的指令必须作用在原生 DOM 元素上才能生效。
从错误堆栈看,问题出现在 <MyPagination> 组件中,其根节点被包裹在 <ElConfigProvider> 组件内,而 <ElConfigProvider> 本身是一个Vue 组件(非原生 DOM 元素)。当父组件在 <MyPagination> 上使用 v-show 时,指令无法正确绑定到原生元素,导致警告。
解决方法:避免在父组件中对子组件使用指令
vue 文件
<template>
<!-- 正确示例:将指令作用到原生元素 -->
<div v-if="showPagination">
<MyPagination />
</div>
</template>
tsx 文件
{
showPaging.value && <MyPagination
layout="total, sizes, prev, pager, next, jumper"
pageSizes={[20, 50, 100]}
v-model:pageSize={params.pageSize}
currentPage={params.pageIndex}
onSize-change={onSizeChange}
onCurrent-change={onCurrentChange}
total={totalCount.value}
/>
}
注意事项:检查 Element Plus 版本
使用最新版本的 Element Plus(如 2.3.3+),避免旧版本组件内部实现导致根节点问题。