vue中引入.svg图标,使用iconfont图标库

阿里巴巴的iconfont是一个很好的图标库,海量的素材可以快速满足开发人员日常对图标的诉求,我们采用symbol引用,官方介绍

创建SvgIcon组件
–components =>SvgIcon=>index.vue

<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>
 
<script>
export default {
    
    
  name: 'svg-icon',
  props: {
    
    
    iconClass: {
    
    
      type: String,
      required: true
    },
    className: {
    
    
      type: String
    }
  },
  computed: {
    
    
    iconName() {
    
    
      return `#icon-${
      
      this.iconClass}`
    },
    svgClass() {
    
    
      if (this.className) {
    
    
        return 'svg-icon ' + this.className
      } else {
    
    
        return 'svg-icon'
      }
    }
  }
}
</script>
 
<style scoped>
.svg-icon {
    
    
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

创建icons文件夹
src跟目录下创建icons文件夹,里面创建svg文件夹和index.js文件在这里插入图片描述

svg文件夹中用来存放各种扩展的.svg图标。
在这里插入图片描述

index.js

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg组件
 
// register globally
Vue.component('svg-icon', SvgIcon)
 
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)

main.js中引入

import './icons'

下载插件

cnpm i svg-sprite-loader --save

配置
在build/webpack.base.conf.js文件中,加入

  {
    
    
    test: /\.svg$/,
    loader: 'svg-sprite-loader',
    include: [resolve('src/icons')],
    options: {
    
    
      symbolId: 'icon-[name]'
    }
  }

并在以下设置中添加exclude: [resolve(‘src/icons’)],如下所示

  {
    
    
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    exclude: [resolve('src/icons')],
    options: {
    
    
      limit: 10000,
      name: utils.assetsPath('img/[name].[hash:7].[ext]')
    }
  },

使用
ok,大功告成,这样就可以在.vue页面中直接使用.svg文件了。使用.svg文件的名称,通过icon-class属性来引用。

<svg-icon icon-class="user" />

后续如果继续需要使用其他的图标直接去阿里巴巴官网下面就好啦!!

扫描二维码关注公众号,回复: 12835602 查看本文章

这里点击下载
在这里插入图片描述
在这里插入图片描述
然后将文件丢到icon文件夹下面
在这里插入图片描述
然后使用

   <svg-icon icon-class="share" />

猜你喜欢

转载自blog.csdn.net/weixin_48371382/article/details/115044735