圖文詳解如何在vue3+vite項(xiàng)目中使用svg
今天在vue3+vite項(xiàng)目練習(xí)中,在使用svg時(shí),發(fā)現(xiàn)之前的寫(xiě)法不能用,之前的使用方法參考vue2中優(yōu)雅的使用svg
const req = require.context('./icons/svg', false, /\.svg$/)
const requireAll = requireContent => requireContent.keys().map(requireContent)
requireAll(req)
然后就各種資料查找,終于實(shí)現(xiàn)了,廢話不多說(shuō),直接上代碼:
stept1: 文件目錄

stept2: 安裝 svg-sprite-loader
npm install svg-sprite-loader -D # via yarn yarn add svg-sprite-loader -D
stept3: 創(chuàng)建svgIcon.vue文件
<template>
<svg :class="svgClass" v-bind="$attrs" :style="{color: color}">
<use :xlink:href="iconName" rel="external nofollow" />
</svg>
</template>
<script setup>
import { defineProps, computed } from "vue";
const props = defineProps({
name: {
type: String,
required: true
},
color: {
type: String,
default: ''
}
})
const iconName = computed(()=>`#icon-${props.name}`);
const svgClass = computed(()=> {
console.log(props.name, 'props.name');
if (props.name) {
return `svg-icon icon-${props.name}`
}
return 'svg-icon'
});
</script>
<style lang='scss'>
.svg-icon {
width: 1em;
height: 1em;
fill: currentColor;
vertical-align: middle;
}
</style>
stept4: 創(chuàng)建icons文件夾,存放svg文件
stept5: 在main.js里面全局注入svg-icon組件
import { createApp } from 'vue'
import App from './App.vue'
import svgIcon from './components/svgIcon.vue'
createApp(App).component('svg-icon', svgIcon).mount('#app');
stept6: 在plugins文件夾創(chuàng)建svgBuilder.js(重點(diǎn)來(lái)了), ts版本參考:https://github.com/JetBrains/svg-sprite-loader/issues/434
import { readFileSync, readdirSync } from 'fs'
let idPerfix = ''
const svgTitle = /<svg([^>+].*?)>/
const clearHeightWidth = /(width|height)="([^>+].*?)"/g
const hasViewBox = /(viewBox="[^>+].*?")/g
const clearReturn = /(\r)|(\n)/g
function findSvgFile(dir) {
const svgRes = []
const dirents = readdirSync(dir, {
withFileTypes: true
})
for (const dirent of dirents) {
if (dirent.isDirectory()) {
svgRes.push(...findSvgFile(dir + dirent.name + '/'))
} else {
const svg = readFileSync(dir + dirent.name)
.toString()
.replace(clearReturn, '')
.replace(svgTitle, ($1, $2) => {
// console.log(++i)
// console.log(dirent.name)
let width = 0
let height = 0
let content = $2.replace(
clearHeightWidth,
(s1, s2, s3) => {
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>')
svgRes.push(svg)
}
}
return svgRes
}
export const svgBuilder = (path, perfix = 'icon') => {
if (path === '') return
idPerfix = perfix
const res = findSvgFile(path)
// console.log(res.length)
// const res = []
return {
name: 'svg-transform',
transformIndexHtml(html) {
return html.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>
`
)
}
}
}
stept7: 最后在vite.config.js修改配置
import { svgBuilder } from './src/plugins/svgBuilder';
export default defineConfig({
plugins: [svgBuilder('./src/icons/svg/')] // 這里已經(jīng)將src/icons/svg/下的svg全部導(dǎo)入,無(wú)需再單獨(dú)導(dǎo)入
})
總結(jié)
到此這篇關(guān)于如何在vue3+vite項(xiàng)目中使用svg的文章就介紹到這了,更多相關(guān)vue3+vite使用svg內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue2?中自定義圖片懶加載指令?v-lazy實(shí)例詳解
這篇文章主要為大家介紹了Vue2?中自定義圖片懶加載指令?v-lazy實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
Vue實(shí)現(xiàn)讓頁(yè)面加載時(shí)請(qǐng)求后臺(tái)接口數(shù)據(jù)
這篇文章主要介紹了Vue實(shí)現(xiàn)讓頁(yè)面加載時(shí)請(qǐng)求后臺(tái)接口數(shù)據(jù)2022-08-08
詳解Vue CLI3 多頁(yè)應(yīng)用實(shí)踐和源碼設(shè)計(jì)
這篇文章主要介紹了詳解Vue CLI3 多頁(yè)應(yīng)用實(shí)踐和源碼設(shè)計(jì),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08
vue之elementUi的el-select同時(shí)獲取value和label的三種方式
這篇文章主要介紹了vue之elementUi的el-select同時(shí)獲取value和label的三種方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
vue項(xiàng)目使用可選鏈操作符編譯報(bào)錯(cuò)問(wèn)題及解決
這篇文章主要介紹了vue項(xiàng)目使用可選鏈操作符編譯報(bào)錯(cuò)問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
Vue 對(duì)象和數(shù)據(jù)的強(qiáng)制更新方式
這篇文章主要介紹了Vue 對(duì)象和數(shù)據(jù)的強(qiáng)制更新方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
使用echarts柱狀圖實(shí)現(xiàn)select下拉刷新數(shù)據(jù)
這篇文章主要介紹了使用echarts柱狀圖實(shí)現(xiàn)select下拉刷新數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10
Vue支持搜索與篩選的用戶列表實(shí)現(xiàn)流程介紹
這篇文章主要介紹了Vue支持搜索與篩選的用戶列表實(shí)現(xiàn)流程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-10-10
在vue中v-for循環(huán)遍歷圖片不顯示錯(cuò)誤的解決方案
這篇文章主要介紹了在vue中v-for循環(huán)遍歷圖片不顯示錯(cuò)誤的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01

