1. vite-plugin-svg-icons插件安装
本文的项目使用vue3+vite来构建,可以使用第三方的vite-plugin-svg-icons插件,来引入svg图标。
# npm
npm i vite-plugin-svg-icons -D
# yarn
yarn add vite-plugin-svg-icons -D
# pnpm
pnpm install vite-plugin-svg-icons -D
配置
vite.config.ts 中配置插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
return {
plugins: [
createSvgIconsPlugin({
// 图标文件夹为src/assets/icons
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
// 指定symbolId格式
symbolId: 'icon-[name]',
],
}
}
在 src/main.ts 内引入注册脚本
import 'virtual:svg-icons-register'
2. 下载svg图标
将下载的svg放入图标目录src/assets/icons
3. 使用svg图标
封装 svg-icon 组件
在 iconfont 官网上可以看到给出了使用svg的示例代码:
<svg class="icon" aria-hidden="true">
<use xlink:href="#icon-xxx"></use>
</svg>
如果每次都按照上面的方式使用,无疑是很麻烦的,可以将其封装成组件,在需要用到的地方直接引入即可。 在 components 目录下新建 SvgIcon 目录,然后新建index.vue 文件。
<template>
<svg
aria-hidden="true"
class="svg-icon"
:width="width"
:height="height"
>
<use
:xlink:href="symbolId"
:fill="color"
/>
</svg>
</template>
<script setup>
import { computed } from 'vue'
const props = defineProps({
name: {
type: String,
required: true
},
color: {
type: String,
default: '#333'
},
width: {
type: String,
default: '16px'
},
height: {
type: String,
default: '16px'
}
})
const symbolId = computed(() => `#icon-${props.name}`)
</script>
全局注册
在 main.ts 里面全局注册,不然每次引用图标的时候还得单独引入一次该组件。
import svgIcon from "@/components/SvgIcon/index.vue";
const app = createApp(App)
app.component('SvgIcon', SvgIcon);
组件中使用
传入需要使用的图标名即可,同时还可以传入颜色,宽度和高度来定义样式。
<template>
<SvgIcon name="icon-circle" color="pink" width="100px" height="100px"></SvgIcon>
</template>