下面是在 Vue 3 項目中完整引入和使用?vite-plugin-svg-icons
?的步驟
1、安裝插件
npm install vite-plugin-svg-icons -D
# 或
yarn add vite-plugin-svg-icons -D
# 或
pnpm add vite-plugin-svg-icons -D
2、配置 Vite
在?vite.config.ts
?或?vite.config.js
?中配置:
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')],// 指定symbolId格式symbolId: 'icon-[name]',// 可選配置svgoOptions: {plugins: [{ name: 'removeAttrs', params: { attrs: ['fill'] } } // 移除svg默認顏色]}})]
})
3. 創建 SVG 組件
<script setup>
import { computed } from 'vue'const props = defineProps({name: {type: String,required: true,},className: {type: String,default: '',},size: {type: [Number, String],default: 15,},circle: {type: Boolean,default: false,},color: String,defaultImg: String,
})
const style = computed(() => {const size = typeof props.size === 'string' ? props.size : `${props.size}px`return {width: size,height: size,borderRadius: props.circle ? '50%' : null,color: props.color,}
})
const symbolId = computed(() => `#icon-${props.name}`)
</script>
<template><svg aria-hidden="true" class="svg-icon" :class="className" :style="style"><use :xlink:href="symbolId" /></svg>
</template>
<style scoped>
.svg-icon {/* width: 30px;height: 30px; */display: inline-block;vertical-align: -2px;fill: currentColor;
}
</style>
4. 全局注冊組件
在?main.js
?中:
import { createApp } from 'vue'
import App from './App.vue'
import 'virtual:svg-icons-register' // 引入注冊腳本
import SvgIcon from '@/components/SvgIcon.vue' // 引入組件const app = createApp(App)// 全局注冊svg組件
app.component('SvgIcon', SvgIcon)app.mount('#app')
5. 使用圖標
-
將 SVG 文件放入?
src/assets/svg
?目錄 -
在組件中使用:
<div class="img-list" v-for="(item, index) in iconlist" :key="index" @click="itemClick(item)"> <div class="default-img"><!-- 在組件中使用 --><SvgIcon :name="item.iconname" size="30" class="svg-icon" /> </div> </div> const list = ref([{iconname: 'float-robot',id: 1},{iconname: 'float-wx',id: 2},{iconname: 'float-tell',id: 3},{iconname: 'float-qq',id: 4},{iconname: 'float-message-board',id: 5} ]) <style scoped lang="scss"> .img-list{padding: 20px;background: #fff;display: flex;flex-direction: column;justify-content: space-between;justify-items: center;height: 330px;cursor: pointer;box-shadow: 0px 0px 14px 0px rgba(0, 0, 0, 0.12);border-radius: 34px;box-sizing: border-box;&:hover {.default-img {.svg-icon {color: #005fff; // 默認顏色fill: currentColor; // 繼承color顏色transition: color 0.3s ease; // 添加過渡效果}}} } </style>
最后看效果:鼠標經過svg圖標變藍色