Vite 中的 Element Plus 和 Icon 图标:按需引入的最佳实践

安装

powershell 复制代码
npm i element-plus @element-plus/icons-vue
npm i -D unplugin-auto-import unplugin-vue-components unplugin-icons

修改

修改您的 vite.config.ts 文件如下:

ts 复制代码
import path from 'path'
import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

const pathSrc = path.resolve(__dirname, 'src')

export default defineConfig({
  resolve: {
    alias: {
      '@': pathSrc,
    },
  },
  plugins: [
    Vue(),
    AutoImport({
      // 自动导入 Vue 相关函数,如:ref, reactive, toRef 等
      imports: ['vue'],
      resolvers: [
        // 自动导入 Element Plus 相关函数,如:ElMessage, ElMessageBox... (带样式)
        ElementPlusResolver(),
        // 自动导入图标组件
        IconsResolver({
          prefix: 'Icon',
        }),
      ],
      dts: path.resolve(pathSrc, 'auto-imports.d.ts')
    }),
    Components({
      resolvers: [
        // 自动注册图标组件
        IconsResolver({
          enabledCollections: ['ep']
        }),
        // 自动导入 Element Plus 组件
        ElementPlusResolver()
      ],
      dts: path.resolve(pathSrc, 'components.d.ts')
    }),
    Icons({
      autoInstall: true
    })
  ]
})

Element Plus使用

Element Plus组件和方法无需显式引入,直接使用即可。否则,可能会导致样式丢失。如果在使用方法时出现类型错误,可以尝试保存并编译项目,插件会自动将类型写入 auto-imports.d.ts 文件,从而避免错误。

Icon图标的使用

  • 在按需引入图标时,模板 <template></template>不应 使用驼峰命名,而应改为使用短横线 - 命名,并在图标名称之前加上 i-ep- 前缀。
html 复制代码
<template>
  <el-icon>
    <!-- 原来是:<CircleCheckFilled /> -->
    <i-ep-circle-check-filled />
  </el-icon>
</template>
  • 有时候,我们需要使用 v-for 来动态绑定图标。在 <script setup lang="ts"></script> 中,使用驼峰命名并加上 IconEp 前缀。请注意,这不是一个字符串,而是一个对象。在模板 <template></template> 中,使用 <component :is="item.icon" /> 进行绑定。
html 复制代码
<template>
  <el-icon v-for="item in menu" :key="item.name">
    <component :is="item.icon" />
  </el-icon>
</template>
<script setup lang="ts">
const menu = [
  {
    name: '增',
    icon: IconEpPlus
  },
  {
    name: '改',
    icon: IconEpEditPen
  },
  {
    name: '删',
    icon: IconEpDelete
  }
]
</script>

参考链接

相关推荐
鹏多多15 小时前
Web浏览器后台离线通知方案实现以及兼容指南
前端·javascript·vue.js
yangmu320315 小时前
Vue3 响应式系统深度解析:从 Proxy 到依赖追踪
前端·javascript·vue.js
VaJoy17 小时前
全面革新⚡️ Vue 3.6 项目工程的基础实现
前端·vue.js
vipbic1 天前
中后台越做越乱后,我用插件化把它救回来了
前端·vue.js
kaiking_g1 天前
vue项目中,静态导入 vs 动态导入 详解
前端·javascript·vue.js
不法2 天前
uniapp map地图导航/地图路线
前端·vue.js·uni-app
帅次2 天前
Android 高级工程师面试:Flutter Widget 体系 近1年高频追问 20 题
android·flutter·面试·element·widget·setstate·renderobject
卓怡学长2 天前
w263基于springboot + vue 健康饮食管理系统
java·数据库·vue.js·spring boot·spring·intellij-idea
无情的西瓜皮2 天前
MCP 协议实战:从零搭建一个 MCP 服务器(Node.js 版)
vue.js·人工智能·typescript·node.js
万亿少女的梦1682 天前
基于Spring Boot、Vue.js和MySQL的超市管理系统设计与实现
java·vue.js·spring boot·mysql·管理系统