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的插件