vite+vue3项目中使用SVG方式

 更新时间:2023年10月08日 09:04:44   作者:加麻加辣多香菜  
这篇文章主要介绍了vite+vue3项目中使用SVG方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

vite+vue3项目中使用SVG

在开发过程中发现在vite+vue3项目中与在vue2项目中使用SVG的方式有所区别。

下面将详细操作记录下来。

首先我们先来看一下项目目录。

stept1

安装svg-sprite-loader

yarn add svg-sprite-loader -D

stept2

在components目录下创建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 ${iconName.value}`
  }
  return "svg-icon"
})
</script>
​
<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
  vertical-align: middle;
}
</style>

stept3

在src目录下创建icons目录,用来存放SVG文件

stept4

在main.js中将我们的SvgIcon组件全局注册

stept5

在src下新建plugins文件夹,创建svgBuilder.js

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>
        `
      )
    }
  }
}

stept6 

在vite.config.js修改配置

stept7 

在项目中使用,name和color必传

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 关于Less在Vue中的使用方法介绍

    关于Less在Vue中的使用方法介绍

    最近发现好多小伙伴在面试的过程中会问到vue如何使用less和scss,所以下面这篇文章主要给大家介绍了关于Less在Vue中的使用方法,需要的朋友可以参考下
    2023-10-10
  • setTimeout在vue中的正确使用方式

    setTimeout在vue中的正确使用方式

    这篇文章主要介绍了setTimeout在vue中的正确使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-01-01
  • 浅谈Vue页面级缓存解决方案feb-alive(上)

    浅谈Vue页面级缓存解决方案feb-alive(上)

    这篇文章主要介绍了浅谈Vue页面级缓存解决方案feb-alive(上),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04
  • Vue 中驼峰命名与短横线分割命名的用法及区别

    Vue 中驼峰命名与短横线分割命名的用法及区别

    在 Vue 中,命名规范是一个非常重要的话题,驼峰命名和短横线分割命名都有其各自的优缺点和适用场景,开发者需要根据实际情况进行选择,这篇文章主要介绍了Vue 中驼峰命名与短横线分割命名作用及区别介绍,需要的朋友可以参考下
    2023-05-05
  • vue-quill-editor 自定义工具栏和自定义图片上传路径操作

    vue-quill-editor 自定义工具栏和自定义图片上传路径操作

    这篇文章主要介绍了vue-quill-editor 自定义工具栏和自定义图片上传路径操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • VUE项目去除input 框值所有空格的操作方法

    VUE项目去除input 框值所有空格的操作方法

    这篇文章主要介绍了VUE项目去除input 框值所有空格的操作方法,主要包括去除空格的方法、正则和element ui写法,本文给大家讲解的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-10-10
  • 详解vue-router的Import异步加载模块问题的解决方案

    详解vue-router的Import异步加载模块问题的解决方案

    这篇文章主要介绍了详解vue-router的Import异步加载模块问题的解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-05-05
  • vue实现修改标签中的内容:id class style

    vue实现修改标签中的内容:id class style

    这篇文章主要介绍了vue实现修改标签中的内容:id class style,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • Vue.js项目部署到服务器的详细步骤

    Vue.js项目部署到服务器的详细步骤

    这篇文章给大家介绍了Vue.js项目部署到服务器的详细步骤,既然是部署到服务器,肯定是需要一个云的。具体思路步骤大家可以参考下本文
    2017-07-07
  • 公共Hooks封装报表导出useExportExcel实现详解

    公共Hooks封装报表导出useExportExcel实现详解

    这篇文章主要为大家介绍了公共Hooks封装报表导出useExportExcel实现详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-12-12

最新评论