集成element-plus
# 集成 Element Plus
在 Vue3 + TypeScript 项目中,我们可以集成 Element Plus
作为 UI 组件库,以提升开发效率和界面美观度。
# 1. 安装 Element Plus
# 使用 pnpm 进行安装
由于 pnpm
具有更快的安装速度和更小的磁盘占用,我们推荐使用:
pnpm install element-plus @element-plus/icons-vue
1
如果你的项目使用 npm
或 yarn
,可以使用:
npm install element-plus @element-plus/icons-vue
# 或
yarn add element-plus @element-plus/icons-vue
1
2
3
2
3
说明
element-plus
:主 UI 组件库,包含 Button、Table、Form 等常用组件。@element-plus/icons-vue
:Element Plus 提供的 官方 Vue 3 图标库,可以直接在组件中使用图标。
# 2. 在 main.ts 中全局注册 Element Plus
入口文件 main.ts
import { createApp } from 'vue';
import App from './App.vue';
// 引入 Element Plus 组件库
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
// 设置 Element Plus 语言为中文
// @ts-ignore 忽略当前文件 ts 类型检查(否则可能会有红色警告)
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
// 创建 Vue 应用实例
const app = createApp(App);
// 全局注册 Element Plus,设置语言
app.use(ElementPlus, { locale: zhCn });
app.mount('#app');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
说明
import ElementPlus from 'element-plus'
:引入Element Plus
组件库。import 'element-plus/dist/index.css'
:引入 Element Plus 的全局样式。import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
:引入 中文语言包,默认Element Plus
是 英文,这里设置为 中文。@ts-ignore
:TypeScript 可能会提示 类型错误,这里忽略该错误,确保不会影响 打包。app.use(ElementPlus, { locale: zhCn })
:全局使用Element Plus
并设置语言。
# 3. 配置 Element Plus 组件的类型支持
在 TypeScript
项目中,默认情况下 Element Plus
的全局组件类型可能不会自动识别,因此我们需要在 tsconfig.json
中手动配置。
# 修改 tsconfig.json
{
"compilerOptions": {
"types": ["element-plus/global"]
}
}
1
2
3
4
5
2
3
4
5
说明
types: ["element-plus/global"]
让 TypeScript 识别Element Plus
的 全局组件类型,例如:<el-button type="primary">按钮</el-button>
1否则 TypeScript 可能会报错 "Cannot find name 'el-button'"。
# 4. 测试 Element Plus 组件
完成以上配置后,我们可以在 App.vue
或其他组件中测试 Element Plus
组件与图标库的使用。
# 使用 Element Plus 组件
<template>
<div>
<el-button type="primary">主要按钮</el-button>
<el-button type="success">成功按钮</el-button>
<el-button type="danger">危险按钮</el-button>
</div>
</template>
1
2
3
4
5
6
7
2
3
4
5
6
7
# 使用 Element Plus 图标
<template>
<div>
<el-icon><Edit /></el-icon>
<el-icon><Delete /></el-icon>
<el-icon><Search /></el-icon>
</div>
</template>
<script setup lang="ts">
import { Edit, Delete, Search } from '@element-plus/icons-vue';
</script>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
说明
- 组件
<el-button>
直接可用,无需额外引入。 - 图标 需要从
@element-plus/icons-vue
按需导入,然后在el-icon
组件中使用<component>
方式嵌套。
编辑此页 (opens new window)