svg图标组件封装

一、安装插件

npm i vite-plugin-svg-icons -D

二、在 vite.config.js中配置

import viteSvgIcons from 'vite-plugin-svg-icons'

import path from 'path'

export default () => {

  return {

    plugins: [

      viteSvgIcons({

        // Specify the icon folder to be cached

        iconDirs: [path.resolve(process.cwd(), 'src/icons')],

        // Specify symbolId format

        symbolId: 'icon-[dir]-[name]'

      })

    ]  

  }

}

三、在 main.js中加入如下代码:

import 'virtual:svg-icons-register'

四、新建 vue 组件:/src/components/SvgIcon.vue

<template>

  <svg :class="svgClass" aria-hidden="true">

    <use :href="symbolId" />

  </svg>

</template>

<script>

  import { defineComponent, computed } from 'vue'

  export default defineComponent({

    name: 'SvgIcon',

    props: {

      prefix: {

        type: String,

        default'icon'

      },

      name: {

        type: String,

        required: true

      },

      className: {

        type: String,

        default''

      }

    },

    setup(props) {

      const symbolId = computed(() => `#${props.prefix}-${props.name}`)

      const svgClass = computed(() => {

        if (props.className) {

          return `svg-icon ${props.className}`

        }

        return 'svg-icon'

      })

      return { symbolId, svgClass }

    }

  })

</script>

<style scope>

  .svg-icon {

    width: 1em;

    height: 1em;

    vertical-align: -0.1em; /* 因icon大小被设置为和字体大小一致,而span等标签的下边缘会和字体的基线对齐,故需设置一个往下的偏移比例,来纠正视觉上的未对齐效果 */

    fill: currentColor; /* 定义元素的颜色,currentColor是一个变量,这个变量的值就表示当前元素的color值,如果当前元素未设置color值,则从父元素继承 */

    overflow: hidden;

  }

</style>

五、src 目录下建立 icons 目录存放 svg 图标

# src/icons

- back.svg

六、页面使用

<header>

  <svg-icon name="back" className="back" @click="backHome"></svg-icon>

</header>

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值