通過vite-plugin-svg-icons 使用SVG圖片

一、安裝 vite-plugin-svg-icons

? ? npm i vite-plugin-svg-icons -D

? ? // 或者

? ? yarn add vite-plugin-svg-icons -D

二、在main.js引入

import 'virtual:svg-icons-register'

三、配置SVG圖片文件夾


四、在vite.config.js中配置

//import path,{ resolve } from 'path'

import path from 'path'

import {createSvgIconsPlugin} from 'vite-plugin-svg-icons'

export default defineConfig((command) => {

return {

? ? plugins: [

? ? ? createSvgIconsPlugin({

? ? ? ? // 指定要緩存的文件夾

? ? ? ? iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],

? ? ? ? // 指定symbolId格式

? ? ? ? symbolId: '[name]'

? ? ? })

? ? ],

}

})

五、新建svg封裝組件,路徑參考:src\components\svg-icon\index.vue

<template>

? <svg :class="svgClass" aria-hidden="true">

? ? <use class="svg-use" :href="symbolId" />

? </svg>

</template>

<script>

? import { defineComponent, computed } from 'vue'

? export default defineComponent({

? ? name: 'SvgIcon',

? ? props: {

? ? ? prefix: {

? ? ? ? type: String,

? ? ? ? default: 'icon'

? ? ? },

? ? ? name: {

? ? ? ? type: String,

? ? ? ? required: true

? ? ? },

? ? ? className: {

? ? ? ? type: String,

? ? ? ? default: ''

? ? ? }

? ? },

? ? setup(props) {

? ? ? const symbolId = computed(() => `#${props.name}`)

? ? ? const svgClass = computed(() => {

? ? ? ? if (props.className) {

? ? ? ? ? return `svg-icon ${props.className}`

? ? ? ? }

? ? ? ? return 'svg-icon'

? ? ? })

? ? ? return { symbolId, svgClass }

? ? }

? })

</script>

<style scope>

? .svg-icon {

? ? vertical-align: -0.1em; /* 因icon大小被設置為和字體大小一致,而span等標簽的下邊緣會和字體的基線對齊,故需設置一個往下的偏移比例,來糾正視覺上的未對齊效果 */

? ? fill: currentColor; /* 定義元素的顏色,currentColor是一個變量,這個變量的值就表示當前元素的color值,如果當前元素未設置color值,則從父元素繼承 */

? ? overflow: hidden;

? }

</style>

六、按需引入使用

<template>

? <SvgIcon name="issue"></SvgIcon>

</template>

<script setup>

import SvgIcon from "@/components/SvgIcon.vue";

</script>

七、全局引入使用

在main.js中加入

import svgIcon from './components/svgIcon/index.vue'

createApp(App).component('svg-icon', svgIcon)

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容