SVG
安装插件
npm i vite-plugin-svg-icons
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { resolve } from 'path'
export default defineConfig({//配置路径别名resolve: {alias: {"@": resolve(__dirname, 'src')}},plugins: [vue(),createSvgIconsPlugin({// svg 图标要统一放在 src/assets/iconsiconDirs: [resolve(process.cwd(), 'src/assets/icons')],symbolId: 'icon-[dir]-[name]',// 配置SVGO优化 可以 通过fill 改变svg图标填充颜色svgoOptions: {multipass: true,plugins: [{name: 'removeAttrs',params: {attrs: ['fill', 'fill-rule']}}]}})]
})
》》mian.ts
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
//svg 插件需要配置的代码
import 'virtual:svg-icons-register'
createApp(App).mount('#app')
定义 svg 组件
//CustSvg.vue
<template><div> // 解构<svg :style="{width,height}"><!-- <use xlink:href="#icon-computer"></use> --> <use :xlink:href="prefix+name" :fill="color"></use> </svg></div>
</template><script setup lang="ts">defineProps({//xlink:href属性的前缀prefix: {type: String,default: '#icon-'},//svg图标名称name: String,//svg 图标填充颜色color: {type: String,default: 'Red'},//svg图标高度height: {type: String,default:'16px'},width: {type: String,default: '16px'}} )</script><style>
</style>
》》在其他组件中使用
import CustSvg from ‘./components/CustSvg.vue’
全局组件
import { createApp } from 'vue'
import './style.css'import App from './App.vue'
//svg 插件需要配置的代码
import 'virtual:svg-icons-register'
import CustSvg from '@/components/CustSvg.vue'
//createApp(App).component("CustSvg",CustSvg).mount('#app') 链式调用
let app = createApp(App)
app.component("CustSvg",CustSvg)
app.mount('#app')
可以通过 插件 统一全部注册全局组件
vue2的插件