本文使用 vue3.js提供的 option-api方式实现

环境

$ node -v
v16.14.0

$ pnpm -v
7.4.1

安装依赖

pnpm

package.json

{
"dependencies": {
"vue": "^3.2.37"
},
"devDependencies": {
"@vitejs/plugin-vue": "^3.0.0",
"fast-glob": "^3.2.11",
"vite": "^3.0.0",
"vite-plugin-svg-icons": "^2.0.1"
}
}

配置文件 vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

export default defineConfig({
plugins: [
vue(),

// 使用svg-icon
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(), 'src/assets/svg/icons')],
// 指定symbolId格式
symbolId: 'icon-[name]',
}),
],

resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
}
})

src/assets/svg/SvgIcon.vue

<template>
<svg
class="svg-icon"
aria-hidden="true"
>
<use
:xlink:href="symbolId"
rel="external nofollow"
/>
</svg>
</template>

<script>// svg 组件
export default {
name: 'svg-icon',

props: {
name: {
type: String,
required: true,
},
},

computed: {
symbolId() {
return `#icon-${this.name}`
},
},
}</script>

<style lang="less">.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}</style>

src/main.js

import { createApp } from 'vue'

// 引入注册脚本
import 'virtual:svg-icons-register'
import SvgIcon from './assets/svg/SvgIcon.vue'

const app = createApp(App)
app.component('svg-icon', SvgIcon)
app.mount('#app')

使用

<svg-icon name="person" />

目录结构

src/assets/svg
SvgIcon.vue
/icons

将svg图标文件放在icons目录下即可