vue 引用字体库iconfont,使用svg,svg组件封装注册使用

本文介绍如何在Vue项目中引入和使用SVG图标,包括配置Webpack处理SVG文件、封装SVG图标组件并实现全局注册,以及如何在项目中具体调用。

引入

  1. public.html 引入在线链接
  2. 下载到本地后main.js 引入 iconfont.js
    在这里插入图片描述
    注意:如果项目开了eslint,可能引入iconfont.js会报错,要设置忽略

使用

<!-- xlink:href 去复制代码所复制出来的东东 -->
<svg class="icon" aria-hidden="true">
  <use xlink:href="#icons-PromptInformation-solid"></use>
</svg>

webpack 识别svg

chainWebpack: (config) => {
    const svgRule = config.module.rule('svg')
    svgRule.uses.clear()
    svgRule
      .oneOf('inline')
      .resourceQuery(/inline/)
      .use('vue-svg-icon-loader')
      .loader('vue-svg-icon-loader')
      .end()
      .end()
      .oneOf('external')
      .use('file-loader')
      .loader('file-loader')
      .options({
        name: 'assets/[name].[hash:8].[ext]'
      })
}

组件封装

// IconSvg.vue
<template>
  <div>
    <svg class="icon" aria-hidden="true">
      <use :xlink:href="iconHref"></use>
    </svg>
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: 'iconSvg',
  props: {
    iconClass: {
      type: String,
      required: true
    }
  },
  computed: {
    iconHref: function () {
      return `#${this.iconClass}`
    }
  }
}
</script>
<style scoped>
.icon {
  width: 2em;
  height: 2em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

全局组件注册

// 引入
import IconSvg from '@/components/IconSvg/IconSvg'
const globalComponents = {
  // 注册
  install (Vue) {
    Vue.component('IconSvg', IconSvg)
  }
}
export default globalComponents
// main.js
import globalComponents from './components/' // global components
Vue.use(globalComponents)`在这里插入代码片`

组件使用

<icon-svg :iconClass="'icona-project-solid'"></icon-svg>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值