vite構(gòu)建的vue3項(xiàng)目中如何使用svg圖標(biāo)?

我們需要借助兩個(gè)插件來(lái)實(shí)現(xiàn):vite-plugin-svg-icons 和 fast-glob
vite-plugin-svg-icons地址: https://github.com/vbenjs/vite-plugin-svg-icons
fast-glob地址:https://github.com/mrmlnc/fast-glob

1、安裝插件:vite-plugin-svg-icons

// 通過(guò)命令安裝2個(gè)插件
npm i vite-plugin-svg-icons -D
npm i fast-glob -D

如圖所示:

//package.json
 "devDependencies": {
    "@types/node": "^18.7.13",
    "@vitejs/plugin-vue": "^3.0.3",
    "fast-glob": "^3.2.12",
    "sass": "^1.54.5",
    "typescript": "^4.6.4",
    "vite": "^3.0.7",
    "vite-plugin-svg-icons": "^2.0.1",
    "vue-tsc": "^0.39.5"
  }

2、配置插件: 在 vite.config.ts中配置 createSvgIconsPlugin

//vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { join, resolve } from "path";
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'


// https://vitejs.dev/config/
export default defineConfig({
  base: "./",
  plugins: [
    vue(),
    createSvgIconsPlugin({
      iconDirs: [resolve(process.cwd(), 'src/assets/svg')],
      symbolId: 'icon-[dir]-[name]',
    }),
    
  ],
  resolve: {
    alias: {
      '@': join(__dirname, 'src'),
    }
  },
})

存放文件路徑 :src/assets/svg

- icon1.svg
- icon2.svg
- icon3.svg
- dir/icon1.svg

然后就在 main.ts 引入下面代碼:

//main.ts
import 'virtual:svg-icons-register'

3、封裝成組件:SvgIcon.vue

<template>
    <svg aria-hidden="true" :style="{ width: size + 'px', height: size + 'px' }">
        <use :xlink:href="symbolId" :fill="color" />
    </svg>
</template>
<script setup lang="ts">
import { computed } from 'vue';

const props = defineProps({
    iconName: {
        type: String,
        required: true
    },
    color: {
        type: String,
        default: ''
    },
    size: {
        type: [Number, String],
        default: 18
    }
})
const symbolId = computed(() => `#icon-${props.iconName}`);

</script>


<style scoped>
.svg-icon {
    fill: currentColor;
    vertical-align: middle;
}
</style>

4、使用方法:

<template>
        <SvgIcon icon-name="icon1" ></SvgIcon>
</template>

<script setup lang="ts">
import SvgIcon from "@/components/SvgIcon.vue";
</script>

<style scoped lang="scss">
</style>
最后編輯于
?著作權(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),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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