39、web前端开发之Vue3保姆教程(三)

发布于:2025-04-11 ⋅ 阅读:(28) ⋅ 点赞:(0)

四、Vue3中集成Element Plus

1、什么是Element Plus

Element Plus 是一款基于 Vue 3 的开源 UI 组件库,旨在为开发者提供一套高质量、易用的组件,用于快速构建现代化的 web 应用程序。

Element Plus 提供了大量的 UI 组件,包括但不限于:

  • 表单组件:输入框、选择器、开关、复选框、单选框等。
  • 数据展示组件:表格、分页、标签、卡片等。
  • 导航组件:按钮、菜单、导航栏、标签页等。
  • 反馈组件:对话框、通知、消息提示框、加载状态等。
  • 其他组件:日期选择器、下拉菜单、树形控件等。

2、Vue中如何使用Element Plus

要将上述配置过程改为使用 TypeScript,需要在你的 Vue 项目中进行一些额外的步骤。首先,确保你的项目已经配置了 TypeScript 支持。以下是如何在 TypeScript 环境下配置和使用 Element Plus 的步骤:

1. 安装依赖

首先,安装 pnpm(如果尚未安装):

npm install -g pnpm

然后,进入项目路径,安装 Element Plus 及其图标库:

查看是否已安装

pnpm list element-plus   

如果 element-plus 没有出现在列表中,说明它并未安装。请安装:

pnpm install element-plus --save
pnpm install @element-plus/icons-vue

2. 配置 main.ts

main.ts 中配置 Vue 应用,并引入 Element Plus 和图标库。注意,使用 TypeScript 需要在文件后缀名中包含 .ts

// main.ts
import {
    createApp } from 'vue';
import App from './App.vue';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';

const app = createApp(App);

// 注册 Element Plus
app.use(ElementPlus);

// 注册 Element Plus 图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
   
  app.component(key, component);
}

app.mount('#app');

3. 在组件中使用

在 TypeScript 环境下,你可以在组件中直接使用 Element Plus 的组件和图标。以下是一个简单的示例:

<template>
  <div>
    <el-button type="primary">按钮</el-button>
    <el-icon><Delete /></el-icon>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { Delete } from '@element-plus/icons-vue';

export default defineComponent({
  name: 'App',
  components: {
    Delete
  }
});
</script>

<style scoped>
/* 你的样式 */
</style>

输入命令

npm run dev

在这里插入图片描述

4. 确保 TypeScript 配置

确保你的 tsconfig.json 文件已经正确配置,支持 Vue 和 TypeScript:

{
   
  "compilerOptions": {
   
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "baseUrl": ".",
    "paths": {