Introduce .svg icon in vue, use iconfont icon library

Alibaba’s iconfont is a very good icon library. Massive materials can quickly meet the daily demands of developers for icons. We use symbol reference, the official introduction

Create SvgIcon component
--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>

Create the icons folder
src and create the icons folder under the directory, create the svg folder and index.js file insideInsert picture description here

The svg folder is used to store various extended .svg icons.
Insert picture description here

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)

Introduced in main.js

import './icons'

Download plugin

cnpm i svg-sprite-loader --save

Configuration
In the build/webpack.base.conf.js file, add

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

And add exclude in the following settings: [resolve('src/icons')], as shown below

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

Use
ok and you're done, so you can use the .svg file directly in the .vue page. Use the name of the .svg file and refer to it through the icon-class attribute.

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

If you continue to use other icons in the future, just go directly to the Alibaba official website! !

Click here to download
Insert picture description here
Insert picture description here
and drop the file under the icon folder
Insert picture description here
and use

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

Guess you like

Origin blog.csdn.net/weixin_48371382/article/details/115044735