vue3+ts+vite项目中引入Element Plus组件和图标的流程

851 阅读2分钟

第一步: 安装Element Plus

image.png

注意:ElementPlus提供了一套Icon 图标,需要单独针对图标进行引入配置,不然图标无法直接使用

方式一:全局引入

全局引入流程较少,直接在main.ts中引入注册即可使用

image.png 接下来根据官网文档示例使用即可

方式二:按需自动导入组件以及样式[推荐,不建议手动】

  1. 引入自动引入element 的插件unplugin-vue-components、unplugin-auto-import
npm install -D unplugin-vue-components unplugin-auto-import
  1. 配置vite.config.ts 文件
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
// ------------ 起点
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// ------------ 终点
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
 plugins: [
   vue(),
   // --------- 起点
   AutoImport({
     resolvers: [
         // 自动导入Element Plus的相关函数
         ElementPlusResolver()
     ],
   }),
   Components({
     resolvers: [
         // 自动导入Element Plus的基础组件(不包括图标)
         ElementPlusResolver()
     ],
   }),
   // ----------- 终点
 ],
})
  1. 在main.ts中引入Element Plus全局样式
import 'element-plus/theme-chalk/src/index.scss'
  1. 使用组件,直接引用就可以了
<template>
  <el-row class="mb-4">
    <el-button>Default</el-button>
    <el-button type="primary">Primary</el-button>
    <el-button type="success">Success</el-button>
    <el-button type="info">Info</el-button>
    <el-button type="warning">Warning</el-button>
    <el-button type="danger">Danger</el-button>
  </el-row>
 </template>

引入Icon图标

安装@element-plus/icons-vue:
# NPM
$ npm install @element-plus/icons-vue
# Yarn
$ yarn add @element-plus/icons-vue
# pnpm
$ pnpm install @element-plus/icons-vue
方式1:导入所有图标并进行全局注册
// main.ts

// 如果您正在使用CDN引入,请删除下面一行。
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
方式2:自动导入,使用 unplugin-icons 和 unplugin-auto-import 从 iconify 中自动导入任何图标集
  • 安装:
npm install -D unplugin-icons unplugin-auto-import
  • 添加 “vite.config.ts” 配置
import IconsResolver from 'unplugin-icons/resolver'
import Icons from 'unplugin-icons/vite'
export default ({ mode }) => {
  return defineConfig({
    plugins: [
      vue(),
      AutoImport({
        resolvers: [
          // 自动导入Element Plus的相关函数
          ElementPlusResolver(),
          // Auto import icon components
         // 自动导入图标组件
          IconsResolver({
            prefix: 'Icon',
          }),
        ]
      }),
      Components({
        resolvers: [
         // Auto register icon components
          // 自动注册图标组件
          IconsResolver({
            enabledCollections: ['ep'],
          }),
        ]
      }),

      Icons({
        autoInstall: true   // 自动安装图标
      }),
   ]
 })
  • 使用图标 官方文档中的引入方式渲染不出来,需要使用以下方式使用
    <i-ep-add-location />
    <i-ep-aim />