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文件夾用來(lái)放置.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)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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