封装前端svg组件

前言:

SVG(Scalable Vector Graphics)是一种基于 XML 的矢量图形格式,它可以在网页上展示高质量的图像,并且可以无损缩放。在前端开发中,SVG 图片被广泛用于创建图标、图形和动画效果。此篇文章将讲述在前端vue项目中封装svg组件,使其svg简单使用。

1. 首先创建svg组件:示例代码

<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script>
export default defineComponent({
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ''
    }
    // color: {
    //   type: String,
    //   default: '#889aa4',
    // },
  },
  setup(props) {
    return {
      iconName: computed(() => `#icon-${props.iconClass}`),
      svgClass: computed(() => {
        if (props.className) {
          return `svg-icon ${props.className}`
        }
        return 'svg-icon'
      })
    }
  }
})
</script>
<style scope lang="scss">
.sub-el-icon,
.nav-icon {
  display: inline-block;
  font-size: 15px;
  margin-right: 12px;
  position: relative;
}

.svg-icon {
  width: 1em;
  height: 1em;
  position: relative;
  fill: currentColor;
  vertical-align: -2px;
}
</style>

其中iconClass代表svg图片名称,需要用到的时候只需要将图片名称传入iconClass属性中即可。

2.此文档使用的是vue3.0+vite架构,所以这边需要下载vite-plugin-svg-icons插件

npm i vite-plugin-svg-icons

3.下载完成插件后需要在vite.config.js中进行配置

首先引入插件 import svgIcons from ‘vite-plugin-svg-icons’ 在配置项中代码

plugins: [
      svgIcons({
         iconDirs: [/* 指定SVG图标文件的目录 */]
       })
     ]

配置 SVG 图标文件路径:默认情况下,vite-plugin-svg-icons 会在 src/icons 目录下寻找 SVG 图标文件。如果你希望指定其他目录,可以在插件的选项中进行配置,配置完成后这个插件会自动生成一个svg组件,也可以自定义svg组件。

4.这边组件选择了挂载到全局,也可以单独引入使用,看个人喜好。

import svgIcon from '@/icons/SvgIcon.vue'
app.component('SvgIcon', svgIcon)

5. 使用

<svg-icon icon-class="tips-icon" class-name="nav-icon" />

作者:邵文俊

猜你喜欢

转载自blog.csdn.net/ekcchina/article/details/131242112
今日推荐