一、搭建vue3+vite项目
npm init vite@latest
二、将svg图片统一放到一个目录中
三、安装插件,自动引入svg文件
-
npm i vite-plugin-svg-icons -D
-
在vite.config.ts中配置
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path';
export default defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
// 指定要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
// 执行icon name的格式
symbolId: 'icon-[name]'
})]
})
npm run dev 如果出现如下报错
解决办法: 安装依赖包
npm i fast-glob -D
三、定义svg组件
- src/components/svgIcon.vue
<script setup lang="ts">
import {computed} from 'vue';
interface Props {
name: string
color?: string
size?: string
}
const props = withDefaults(defineProps<Props>(), {
name: '',
color: '#000',
size: '16px',
})
const iconName = computed(() => `#icon-${props.name}`)
</script>
<template>
<svg class="c-icon" aria-hidden="true">
<use :xlink:href="iconName" :fill="color" />
</svg>
</template>
<style scoped lang="less">
.c-icon {
width: v-bind(size);
height: v-bind(size);
position: relative;
}
</style>
四、全局注册svg组件
- main.ts中
import { createApp } from 'vue';
import App from './App.vue';
// 注册自定义svg组件
import 'virtual:svg-icons-register';
import svgIcon from './components/svgIcon.vue';
const app = createApp(App);
app.component('svgIcon', svgIcon);
app.mount('#app')
五、使用svgIcon组件
<script setup lang="ts">
</script>
<template>
<svgIcon :name="'bin'"/>
</template>
<style scoped>
</style>
六、效果