封装公用svg图标

首先创建一个 index.vue 新组件

<template>
  <svg
    class="svg-icon"
    :class="svgClass"
    :style="{ width: width + 'px', height: height + 'px' }"
    aria-hidden="true"
  >
    <use :xlink:href="iconName" />
  </svg>
</template>

<script>
export default {
  name: "SvgIcon",
  props: {
    name: {
      type: String,
      required: true,
    },
    width: {
      type: Number,
      default: 40,
    },
    height: {
      type: Number,
      default: 40,
    },
  },
  computed: {
    iconName() {
      return `#icon-${this.name}`;
    },
    svgClass() {
      if (this.name) {
        return "svg-icon" + this.name;
      } else {
        return "svg-icon";
      }
    },
  },
};
</script>

<style scoped>
.svg-icon {
  width: 100px;
  height: 100px;
  fill: currentColor;
  overflow: hidden;
}
</style>

其次要注册该组件

import Vue from 'vue'
import SvgIcon from './index.vue' // 引用新组件

// register globally
Vue.component('svg-icon', SvgIcon)

const req = require.context('@/assets/svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

最后直接在vue文件使用

<svg-icon
    name="kafkasource"
	:width="14"
	:height="12"
	/>
						
// name表示命名的svg图标文件名称
// width、height表示图标大小

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值