在 Vue2 项目中按需引入 Element UI 的 Empty 组件 (el-empty
),可以按照以下步骤操作:
完整解决方案
1. 安装必要依赖
npm install element-ui babel-plugin-component -D
# 或
yarn add element-ui babel-plugin-component -D
2. 配置 Babel (.babelrc
或 babel.config.js
)
{
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
3. 在 Vue 文件中按需引入 Empty 组件
<template>
<el-empty description="暂无数据"></el-empty>
</template>
<script>
import { Empty } from 'element-ui'
export default {
components: {
[Empty.name]: Empty
}
}
</script>
备选方案(如果自动引入样式失败)
<template>
<el-empty description="自定义描述"></el-empty>
</template>
<script>
import 'element-ui/lib/theme-chalk/empty.css' // 手动引入样式
import { Empty } from 'element-ui'
export default {
components: {
[Empty.name]: Empty
}
}
</script>
全局注册方式(在 main.js 中)
import Vue from 'vue'
import { Empty } from 'element-ui'
// 方式1:使用 Vue.use()
Vue.use(Empty)
// 方式2:单独注册组件
// Vue.component(Empty.name, Empty)
解决常见问题
-
样式文件路径错误:
// 错误 ❌ import 'element-ui/lib/theme-chalk/el-empty.css' // 正确 ✅ import 'element-ui/lib/theme-chalk/empty.css' // 注意文件名是 empty.css
-
版本问题:
npm install element-ui@2.15.14 --save # 确保使用 2.13.0+ 版本
-
构建配置检查:
// vue.config.js module.exports = { transpileDependencies: ['element-ui'] // 确保 Element UI 被正确转译 }
-
清理缓存:
rm -rf node_modules/.cache # 清除构建缓存 npm install
完整示例组件
<template>
<div class="container">
<el-empty
image="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png"
description="您还没有订单"
>
<el-button type="primary">立即创建</el-button>
</el-empty>
</div>
</template>
<script>
import { Empty, Button } from 'element-ui'
export default {
components: {
[Empty.name]: Empty,
[Button.name]: Button
}
}
</script>
<style scoped>
.container {
padding: 20px;
background: #fff;
border-radius: 4px;
}
</style>
注意事项
- Element UI 的 Empty 组件在 v2.13.0 版本引入,确保你的版本 >= 2.13.0
- 使用
babel-plugin-component
时,样式文件名是empty.css
而不是el-empty.css
- 如果使用 TypeScript,在
tsconfig.json
中添加:{ "compilerOptions": { "moduleResolution": "node" } }
按照以上步骤操作后,el-empty
组件应该能正确显示且不会出现样式缺失的错误。