在项目中引入svg图标

1.在项目中创建icons文件夹

 

 

 

2.在 icons 文件夹下创建 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)

3. 创建 svg 引入方式 工具类

 

 

 内容如下

<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: 1.2em;
  height: 1.2em;
  vertical-align: -0.18em;
  fill: currentColor;
  overflow: hidden;
}
</style>

 4. 将 svg 配置到 webpack

 

 

 

内容如下

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

5.在vue中引入 svg

 在 main.js 入口文件

  

import '@/icons' // icon
6. 使用
 1 <svg-icon class="total-icon" iconClass="zhanghaozongshu" /> 
 
 
 

 

posted @ 2021-05-31 16:30  zzzzzyyyyyy  阅读(613)  评论(0编辑  收藏  举报