美文网首页
Vue使用svg-sprite-loader图标

Vue使用svg-sprite-loader图标

作者: 双耳云 | 来源:发表于2019-07-09 17:39 被阅读0次

1.安装svg-sprite-loade

npm install svg-sprite-loader

2.在webpack.base.conf.js配置中加入

{
        test: /\.svg$/,
        loader: 'svg-sprite-loader',
        include: [resolve('src/assets/icons')],
        options: {
          symbolId: 'icon-[name]'
        }
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        exclude: [resolve('src/assets/icons')], //排除该目录
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },

3.添加组件:src/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>

4.在src/assets目录下建立文件夹/icons/svg,存放图标,src/assets/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)

5.在main.js中全局引入icons

import './assets/icons/index' 

6.使用icon

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

7.运行项目

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

相关文章

网友评论

      本文标题:Vue使用svg-sprite-loader图标

      本文链接:https://www.haomeiwen.com/subject/mpdfkctx.html