如何在vue2+webpack项目中使用svgIcon?参考:手摸手,带你优雅的使用 icon - 掘金
这篇文章主要介绍如何在vue3项目中优雅的使用图标
1、安装插件
node version: >=12.0.0
vite version: >=2.0.0
npm i vite-plugin-svg-icons -D
插件地址:GitHub - vbenjs/vite-plugin-svg-icons: Vite Plugin for fast creating SVG sprites.
2、配置 vite.config.ts
//插件引入
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
plugins: [
vue(),
Components({
// UI库
resolvers: [ArcoResolver()],
}),
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
// 指定symbolId格式
symbolId: "icon-[name]",
/**
* 自定义插入位置
* @default: body-last
*/
// inject?: 'body-last' | 'body-first'
/**
* custom dom id
* @default: __svg__icons__dom__
*/
// customDomId: '__svg__icons__dom__',
}),
],
3、配置 tsconfig.json
如果你使用的 Typescript
, 可以在 tsconfig.json
配置文件中添加
// tsconfig.json
{
"compilerOptions": {
"types": ["vite-plugin-svg-icons/client"]
}
}
4、封装SvgIcon组件 src/components/SvgIcon
<template>
<svg :class="svgClass" a aria-hidden="true">
<use :href="symbolId" />
</svg>
</template>
<script>
import { defineComponent, computed } from 'vue'
export default defineComponent({
name: 'SvgIcon',
props: {
prefix: {
type: String,
default: 'icon',
},
iconClass: {
type: String,
required: true,
},
className: {
type: String,
default: ''
},
color: {
type: String,
default: '#333',
},
},
setup(props) {
const symbolId = computed(() => `#${props.prefix}-${props.iconClass}`)
const svgClass = computed(() => {
if (props.className) {
return 'svg-icon ' + props.className
} else {
return 'svg-icon'
}
})
return { symbolId ,svgClass}
},
})
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover!important;
display: inline-block;
}
</style>
5、同文件夹下创建 index.ts
import { App } from "vue";
import SvgIcon from "./SvgIcon";
import "virtual:svg-icons-register";
const svgIconPlugin = {
install(app: App): void {
// 全局挂载
app.component("svg-icon", SvgIcon);
},
};
export default svgIconPlugin;
6、全局注册 main.ts
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router/router";
// svg封装插件
import svgIcon from "@/components/svgIcon";
createApp(App)
.use(router)
.use(svgIcon)
.mount("#app");
7、组件中使用
// 只需name绑定成icons目录下的svg文件名即可
<svg-icon icon-class="heSuan" />