圖文詳解如何在vue3+vite項(xiàng)目中使用svg
今天在vue3+vite項(xiàng)目練習(xí)中,在使用svg時(shí),發(fā)現(xiàn)之前的寫法不能用,之前的使用方法參考vue2中優(yōu)雅的使用svg
const req = require.context('./icons/svg', false, /\.svg$/)
const requireAll = requireContent => requireContent.keys().map(requireContent)
requireAll(req)
然后就各種資料查找,終于實(shí)現(xiàn)了,廢話不多說,直接上代碼:
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)來了), 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)入,無需再單獨(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)文章
Vue實(shí)現(xiàn)倒計(jì)時(shí)小功能
這篇文章主要為大家詳細(xì)介紹了Vue實(shí)現(xiàn)倒計(jì)時(shí)小功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
vue項(xiàng)目創(chuàng)建步驟及路由router
本文主要給大家分享了vue項(xiàng)目的創(chuàng)建步驟以及vue路由router的相關(guān)知識(shí)點(diǎn),非常的實(shí)用,有需要的小伙伴可以來參考下2020-01-01
vue打包之后配置統(tǒng)一請(qǐng)求地址步驟詳解
這篇文章主要為大家介紹了vue打包之后配置統(tǒng)一請(qǐng)求地址實(shí)現(xiàn)步驟詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
vue數(shù)據(jù)監(jiān)聽解析Object.defineProperty與Proxy區(qū)別
這篇文章主要為大家介紹了vue數(shù)據(jù)監(jiān)聽解析Object.defineProperty Proxy源碼示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
vue3+Element Plus實(shí)現(xiàn)自定義穿梭框的詳細(xì)代碼
找到一個(gè)好用的vue樹形穿梭框組件都很難,又不想僅僅因?yàn)橐粋€(gè)穿梭框在element-ui之外其他重量級(jí)插件,本文給大家分享vue3+Element Plus實(shí)現(xiàn)自定義穿梭框的示例代碼,感興趣的朋友一起看看吧2024-01-01
vue3?中的toRef函數(shù)和toRefs函數(shù)的基本使用
這篇文章主要介紹了vue3?toRef函數(shù)和toRefs函數(shù),文中介紹了ref和toRef的區(qū)別,ref本質(zhì)是拷貝,修改響應(yīng)式數(shù)據(jù)不會(huì)影響原始數(shù)據(jù),toRef的本質(zhì)是引用關(guān)系,修改響應(yīng)式數(shù)據(jù)會(huì)影響原始數(shù)據(jù),需要的朋友可以參考下2022-11-11

