其实vue3内用icon也有多个方法,比较简单的就是element-plus
里面的图标直接使用咯!另外一种自定义的就需要用到 vite-plugin-purge-icons
一、element-plus 使用
vue3的话和vue2不同,2直接加class就完事了!3的话需要先引入,再使用
1、按需使用
import { Setting } from "@element-plus/icons-vue";
这样的话每次需要使用图标,就引入一下即可!
2、全局使用
在main.js
里面全部引入即可
// main.js || main.ts import * as ElementPlusIconsVue from '@element-plus/icons-vue' const app = createApp(App) for (const [key, component] of Object.entries(ElementPlusIconsVue)) { app.component(key, component) }
使用方法
<el-icon> <setting /> </el-icon>
二、自定义icon的svg
vue2采用的是svg-sprite-loader
来进行把文件导入成base64展示!
vue3则需要引入 vite-plugin-purge-icons
来使用
1、下载组件
npm i @iconify/iconify npm i vite-plugin-purge-icons @iconify/json -D
2、修改配置项
// vite.config.js import PurgeIcons from 'vite-plugin-purge-icons' export default { plugins: [ PurgeIcons({ /* PurgeIcons Options */ }) ] }
3、新建组件
//components/index.ts import Icon from './Icon.vue'; export { Icon };
// components/Icon.vue <template> <span ref="elRef" class="anticon"></span> </template> <script lang="ts" setup> import Iconify from "@purge-icons/generated"; import { nextTick, ref, unref, watchEffect } from "vue"; const props = defineProps({ name: { type: String, default: () => "", }, prefix: { type: String, default: () => "ant-design", }, }); const elRef = ref<Element>(); const update = async () => { const el = unref(elRef); if (!el) return; await nextTick(); const icon = props.prefix + ":" + props.name; if (!icon) return; const svg = Iconify.renderSVG(icon, { width: "1.2em", height: "1.2em", }); if (svg) { el.textContent = ""; el.appendChild(svg); } else { const span = document.createElement("span"); span.className = "iconify"; span.dataset.icon = icon; el.textContent = ""; el.appendChild(span); } }; watchEffect(() => update()); </script>