vue3封装icon图标组件

1.创建utils文件夹,在utils文件夹中创建validata.js,判断图标是否为外部资源。

validata.js:

// 判断是否为外部资源
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

2.在components中创建SvgIcon文件夹,在SvgIcon文件夹中创建index.vue。

index.vue:

<template>
  <!-- 展示外部图标 -->
  <div
    v-if="isExternal"
    :style="styleExternalIcon"
    class="svg-external-icon svg-icon"
    :class="className"
  ></div>

  <!-- 展示内部图标 -->
  <svg v-else class="svg-icon" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<script setup>
import { defineProps, computed } from 'vue'
import { isExternal as external } from '@/utils/validate'

const props = defineProps({
  icon: {
    type: String,
    required: true
  },
  className: {
    type: String,
    default: ''
  }
})

// 判断当前图标是否为外部图标
const isExternal = computed(() => external(props.icon))

// 外部图标样式
const styleExternalIcon = computed(() => ({
  mask: `url(${props.icon}) no-repeat 50% 50%`,
  '-webket-mask': `url(${props.icon}) no-repeat 50% 50%`
}))

// 内部图标
const iconName = computed(() => `#icon-${props.icon}`)
</script>

<style lang="scss" scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  mask-size: cover !important;
  display: inline-block;
  background-color: currentColor;
}
</style>

3.使用

ps:如果是iconfont上的图标,需要在public中的html引入链接,点进去有iconfont教程,请参考symbol 引用。

iconfont-阿里巴巴矢量图标库

import SvgIcon from '@/components/SvgIcon/index.vue'
<span class="svg-container">
    <svg-icon icon="yonghu-xianxing"></svg-icon>
</span>

4.全局引入

(1) 在src目录下创建icons文件夹,创建svg子文件夹放svg矢量图,并在icons文件夹下创建文件index.js。

index.js:

import SvgIcon from '@/components/SvgIcon'
// 导入所有的svg图标
const svgRequire = require.context('./svg', false, /\.svg$/)
svgRequire.keys().forEach((svgIcon) => svgRequire(svgIcon))
// console.log(svgRequire.keys())

export default (app) => {
  app.component('svg-icon', SvgIcon)
}

(2) 在main.js中引入上面创建的文件,并全局挂载。

import installIcons from '@/icons'
installIcons(app)

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值