圖文詳解如何在vue3+vite項目中使用svg
今天在vue3+vite項目練習(xí)中,在使用svg時,發(fā)現(xiàn)之前的寫法不能用,之前的使用方法參考vue2中優(yōu)雅的使用svg
const req = require.context('./icons/svg', false, /\.svg$/) const requireAll = requireContent => requireContent.keys().map(requireContent) requireAll(req)
然后就各種資料查找,終于實現(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(重點來了), 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ǎo)入 })
總結(jié)
到此這篇關(guān)于如何在vue3+vite項目中使用svg的文章就介紹到這了,更多相關(guān)vue3+vite使用svg內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue數(shù)據(jù)監(jiān)聽解析Object.defineProperty與Proxy區(qū)別
這篇文章主要為大家介紹了vue數(shù)據(jù)監(jiān)聽解析Object.defineProperty Proxy源碼示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03vue3+Element Plus實現(xiàn)自定義穿梭框的詳細代碼
找到一個好用的vue樹形穿梭框組件都很難,又不想僅僅因為一個穿梭框在element-ui之外其他重量級插件,本文給大家分享vue3+Element Plus實現(xiàn)自定義穿梭框的示例代碼,感興趣的朋友一起看看吧2024-01-01vue3?中的toRef函數(shù)和toRefs函數(shù)的基本使用
這篇文章主要介紹了vue3?toRef函數(shù)和toRefs函數(shù),文中介紹了ref和toRef的區(qū)別,ref本質(zhì)是拷貝,修改響應(yīng)式數(shù)據(jù)不會影響原始數(shù)據(jù),toRef的本質(zhì)是引用關(guān)系,修改響應(yīng)式數(shù)據(jù)會影響原始數(shù)據(jù),需要的朋友可以參考下2022-11-11