在vue3+vite+ ts 项目中使用svg
生活随笔
收集整理的這篇文章主要介紹了
在vue3+vite+ ts 项目中使用svg
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一:components下新建svgIcon.vue文件
<template> <svg :class="svgClass" v-bind="$attrs" :style="style"><use :xlink:href="iconName" /></svg> </template><script lang="ts"> import { computed } from 'vue' import { defineComponent} from 'vue' export default defineComponent({props: {name: {type: String,required: true,},style: {type: Object,default: '',},},setup(props) {const iconName = computed(()=>`#icon-${props.name}`);const svgClass = computed(() => {if (props.name) {return `svg-icon icon-${props.name}`}return 'svg-icon'})return {svgClass,iconName}}, }) </script><style> .svg-icon { fill: currentColor;vertical-align: middle; } </style>二: 創(chuàng)建icons文件夾,存放svg文件
三:在main.ts里面全局注入svg-icon組件
// 注入svg import svgIcon from './components/svgIcon.vue' app.component('svg-icon', svgIcon)四: 在plugins文件夾創(chuàng)建svgBuilder.js
import { readFileSync, readdirSync } from 'fs'let idPerfix = '' const svgTitle = /<svg([^>+].*?)>/ const clearHeightWidth = /(width|height)="([^>+].*?)"/gconst hasViewBox = /(viewBox="[^>+].*?")/gconst clearReturn = /(\r)|(\n)/gfunction 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 = 0let height = 0let 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 === '') returnidPerfix = perfixconst 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>`)}} }五: 最后在vite.config.ts修改配置
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)入 })六: 在頁面中使用
<svg-icon name="aa" :style='style' ></svg-icon><script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({name: 'HelloWorld', setup: () => {const style = {width: '50px'}return { style }} }) </script>總結(jié)
以上是生活随笔為你收集整理的在vue3+vite+ ts 项目中使用svg的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 春江花月夜原文赏析翻译
- 下一篇: 如何利用废旧路由器进行信号增强 旧路由器