Vue3中使用svg圖標(biāo)

  • Vue3+vite+ts
    -安裝依賴
npm install svg-sprite-loader
yarn add svg-sprite-loader
  • 創(chuàng)建需要使用到的文件(目錄)
    這邊我是在src目錄下的components文件下創(chuàng)建的svgIcon文件夾仇祭,svgIcon文件夾內(nèi)創(chuàng)建index.vue文件svgFn.ts文件,分別放置組件和核心ts代碼锣险,另外創(chuàng)建一個(gè)svg-icons文件夾用來放置.svg文件
    文件目錄
  • index.vue文件代碼
<template>
  <svg
    :class="svgClass"
    v-bind="$attrs"
    :style="{ color: color, width: w, height: h }"
  >
    <use :xlink:href="iconName"></use>
  </svg>
</template>
<script setup lang="ts">
import { computed, defineProps } from "vue";
/*
 * name  名字 必填
 * color 顏色
 * w     寬度
 * h     高度
 */
const props = defineProps({
  name: {
    type: String,
    required: true,
  },
  color: {
    type: String,
    default: "",
  },
  w: {
    type: String,
    default: "1rem",
  },
  h: {
    type: String,
    default: "1rem",
  },
});
console.log(props.name, props.color);
const iconName = computed(() => `#icon-${props.name}`);
const svgClass = computed(() => {
  if (props.name) return `svg-icon icon-${props.name}`;
  return "svg-icon";
});
</script>
<style scoped>
.svg-icon {
  /* 此屬性為更改svg顏色屬性設(shè)置 */
  fill: currentColor;
  vertical-align: middle;
}
</style>
  • svgFn.ts文件代碼
import { readFileSync, readdirSync } from 'fs'
let idPerfix = ''
const svgTitle = /<svg([^>+].*?)>/
const clearHeightWidth = /(width|height)="([^>+].*?)"/g
const hasViewBox = /(viewBox="[^>+].*?")/g
const clearReturn = /(\r)|(\n)/g
// 查找svg文件
const svgFind = (e: any): any => {
    const arr = []
    const dirents = readdirSync(e, { withFileTypes: true })
    for (const dirent of dirents) {
        if (dirent.isDirectory()) arr.push(...svgFind(e + dirent.name + '/'))
        else {
            const svg = readFileSync(e + dirent.name)
                .toString()
                .replace(clearReturn, '')
                .replace(svgTitle, ($1, $2) => {
                    let width = 0,
                        height = 0,
                        content = $2.replace(clearHeightWidth, (s1: any, s2: any, s3: any) => {
                            if (s2 === 'width') width = s3
                            else if (s2 === 'height') height = s3
                            return ''
                        })
                    if (!hasViewBox.test($2)) content += `viewBox="0 0 ${width} ${height}"`
                    return `<symbol id="${idPerfix}-${dirent.name.replace('.svg', '')}" ${content}>`
                }).replace('</svg>', '</symbol>')
            arr.push(svg)
        }
    }
    return arr
}
// 生成svg
export const createSvg = (path: any, perfix = 'icon') => {
    if (path === '') return
    idPerfix = perfix
    const res = svgFind(path)
    return {
        name: 'svg-transform',
        transformIndexHtml(dom: String) {
            return dom.replace(
                '<body>',
                `<body><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">${res.join('')}</svg>`
            )
        }
    }
}
  • 在 main.ts文件中設(shè)置svg-icon為全局組件
import { createApp } from 'vue'
import svgIcon from '@/components/svgIcon/index.vue'
import App from './App.vue'
const app = createApp(App)
app.component('svg-icon', svgIcon)
app.mount('#app')
  • vite-config.ts 文件中添加配置
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

//引入核心ts文件
import { createSvg } from './src/components/svgIcon/svgFn'

export default defineConfig({
  plugins:[{
    vue(),
    //路徑指向 .svg 文件夾
    createSvg('./src/components/svgIcon/svg-icons/')
  }]
})
<svg-icon name="admin" color="#0094ff"></svg-icon>
示例

記錄完畢!參考文章參考文章

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末眉抬,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子贬芥,更是在濱河造成了極大的恐慌吐辙,老刑警劉巖宣决,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蘸劈,死亡現(xiàn)場離奇詭異,居然都是意外死亡尊沸,警方通過查閱死者的電腦和手機(jī)威沫,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來洼专,“玉大人棒掠,你說我怎么就攤上這事∑ㄉ蹋” “怎么了烟很?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我雾袱,道長恤筛,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任芹橡,我火速辦了婚禮毒坛,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘林说。我一直安慰自己煎殷,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布腿箩。 她就那樣靜靜地躺著豪直,像睡著了一般。 火紅的嫁衣襯著肌膚如雪珠移。 梳的紋絲不亂的頭發(fā)上顶伞,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天,我揣著相機(jī)與錄音剑梳,去河邊找鬼唆貌。 笑死,一個(gè)胖子當(dāng)著我的面吹牛垢乙,可吹牛的內(nèi)容都是我干的锨咙。 我是一名探鬼主播,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼追逮,長吁一口氣:“原來是場噩夢啊……” “哼酪刀!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起钮孵,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤骂倘,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后巴席,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體历涝,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年漾唉,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了荧库。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,503評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡赵刑,死狀恐怖分衫,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情般此,我是刑警寧澤蚪战,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布牵现,位于F島的核電站,受9級特大地震影響邀桑,放射性物質(zhì)發(fā)生泄漏施籍。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一概漱、第九天 我趴在偏房一處隱蔽的房頂上張望丑慎。 院中可真熱鬧,春花似錦瓤摧、人聲如沸竿裂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽腻异。三九已至,卻和暖如春这揣,著一層夾襖步出監(jiān)牢的瞬間悔常,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工给赞, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留机打,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓片迅,卻偏偏與公主長得像残邀,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子柑蛇,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,512評論 2 359

推薦閱讀更多精彩內(nèi)容