vite全局使用svg圖標(biāo)組件

版本

"vue": "^3.2.47",
"vite": "^4.1.4",
"vite-plugin-svg-icons": "^2.0.1"

件使用方式

安裝插件

cnpm i vite-plugin-svg-icons -D

修改 vite.config.js 配置文件

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// 配置全局加載svg圖標(biāo)為組件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import path from 'path';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    // 添加以下6行,并根據(jù)自己需求進(jìn)行配置
    createSvgIconsPlugin({
      // 指定需要緩存的圖標(biāo)文件夾
      iconDirs: [path.resolve(process.cwd(), 'src/plugins/svg-icon/svgs')],
      // 指定symbolId格式
      symbolId: '[name]',
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

在 src/icons/ 目錄下新建 SvgIcon.vue ,并添加如下內(nèi)容

使用了setup語(yǔ)法糖寫(xiě)法

<template>
  <svg class="svg-icon" aria-hidden="true" :width="width" :height="height">
    <use :xlink:href="symbolId" :fill="fill" />
  </svg>
</template>

<!-- SvgIcon組件,可將svg圖標(biāo)直接當(dāng)組件使用 -->
<script setup>
import { defineProps, computed } from 'vue'

/**
 * 輸入屬性             類(lèi)型                默認(rèn)值              是否必選                描述
 *  name              string             undefined              是                  svg圖標(biāo)名字
 *  width             number                19                  否                  svg圖標(biāo)寬度
 *  height            number                19                  否                  svg圖標(biāo)高度
 *  fill              string              #ffffff               否                  svg圖標(biāo)填充顏色
 */


const props = defineProps({
  name: {
    type: String,
    required: true
  },
  width: {
    type: Number,
    default: 19
  },
  height: {
    type: Number,
    default: 19
  },
  fill: {
    type: String,
    default: '#ffffff'
  }
})

// 獲取svg圖標(biāo)名稱(chēng),需要和vite.config.js中的配置保持一致
const symbolId = computed(() => `#${props.name}`)
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

src/icons/ 目錄下新建 svg文件夾,并將需要用到的svg圖標(biāo)放入其中

image.png

src/icons/ 目錄下新建 index.js ,并添加如下內(nèi)容

import SvgIcon from './SvgIcon.vue'
import 'virtual:svg-icons-register'
/**
 * Svg圖標(biāo)插件
 */

export default {
  install: (app) => {
    // 注冊(cè)全局組件
    app.component('svg-icon', SvgIcon)
  }
}

全局注冊(cè) SvgIcon 組件,在 main.js 中新增

import svgIcon from './icons';
....
const app = createApp(App);
app.use(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),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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