Vite使用svg組件

1. 增加svg組件

<template>
    <svg
        class="svg-icon"
        aria-hidden="true"
        :style="{
            width: props.size + 'px',
            height: props.size + 'px',
            color: props.color
        }"
    >
        <use :xlink:href="`#icon-${props.name}`" :fill="props.color" />
    </svg>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
/**
 * @description: svg圖標(biāo)組件
 * @use {*} <SvgIcon name="home" :size="14" color="red" />
 */
export default defineComponent({
    name: 'SvgIcon',
    props: {
        name: {
            type: String,
            required: true
        },
        size: {
            type: Number,
            default: 14
        },
        color: {
            type: String,
            default: '#000'
        }
    },
    setup(props) {
        return {
            props
        }
    }
})
</script>
<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: middle;
  fill: currentColor;
  overflow: hidden;
}
</style>

2. 安裝插件 npm i vite-plugin-svg-icons --save-dev

3. 修改 vite.config.js 配置文件

// 配置全局加載svg圖標(biāo)為組件
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({
      // 要緩存的圖標(biāo)文件夾
      iconDirs: [path.resolve(__dirname, 'src/assets/svg')],
      // 執(zhí)行 icon name 的格式
      symbolId: 'icon-[name]'
    })
  ]
})

4. main.ts

import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// svg組件
import 'virtual:svg-icons-register'
import SvgIcon from './SvgIcon.vue'
app.component('SvgIcon', SvgIcon)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過簡信或評(píng)論聯(lián)系作者。

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

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