封裝全局icon組件 svg (仿造element-ui源碼)

1、引入  svg-sprite-loader 插件

npm install svg-sprite-loader --save-dev

vue-cli項目默認狀況下會使用 url-loader 對svg進行處理,會將它放在/img 目錄下,因此這時候咱們引入svg-sprite-loader 會引起一些衝突。vue

//默認`vue-cli` 對svg作的處理,正則匹配後綴名爲.svg的文件,匹配成功以後使用 url-loader 進行處理。
{
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    options: {
        limit: 10000,
        name: utils.assetsPath('img/[name].[hash:7].[ext]')
    }
}

解決方案:使用 webpack 的 exclude和 include,讓svg-sprite-loader只處理你指定文件夾下面的 svg,url-loaer只處理除此文件夾以外的因此 svg,這樣就完美解決了以前衝突的問題。對配置文件進行如下修改:webpack

{
  test: /\.svg$/,
  loader: 'svg-sprite-loader',
  include:[resolve('src/assets/icons')],
  options: {
    symbolId: 'icon-[name]',
    name: utils.assetsPath('img/[name].[hash:7].[ext]')
  }
},
{
  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]')
  }
},

2、創建全局組件

創建vue-cli項目,在src/components下創建icon-svg.vue文件。web

<template>
  <svg class="svg-icon" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<script>
export default {
  name: 'icon-svg',
  props: {
    iconClass: {
      type: String,
      required: true
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}` // 與配置文件的配置格式一致
    }
  }
}
</script>

<style>
.svg-icon {
  width: 50px;
  height: 50px;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

在入口文件全局註冊組件正則表達式

//引入svg組件
import IconSvg from '@/components/icon-svg'

//全局註冊icon-svg
Vue.component('icon-svg', IconSvg)

操做完成以後就能夠在vue文件中使用svg圖標了:vue-cli

import '@/assets/icons/attach_excel.svg'; //引入圖標

直接使用
<svg><use xlink:href="#icon-attach_excel"/></svg>

全局組件形式使用
<icon-svg iconClass="attach_excel"></icon-svg>

3、添加自動導入svg文件

首先咱們建立一個專門放置圖標 icon 的文件夾如:@/src/icons,將全部 icon 放在這個文件夾下。

以後咱們就要使用到 webpack 的 require.context:npm

require.context("./test", false, /.test.js$/);
這行代碼就會去 test 文件夾(不包含子目錄)下面的找全部文件名以 .test.js 結尾的文件能被 require 的文件。
即咱們能夠經過正則匹配引入相應的文件模塊。

require.context有三個參數:segmentfault

  • directory:說明須要檢索的目錄
  • useSubdirectories:是否檢索子目錄
  • regExp: 匹配文件的正則表達式

接下來能夠在入口文件這樣寫,來自動引入 @/src/icons 下面全部的圖標:svg

const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('@/assets/icons', true, /\.svg$/)
requireAll(req)

vue文件直接使用:ui

<icon-svg iconClass="attach_excel"></icon-svg>

 

 

參考網址:http://www.javashuo.com/article/p-oixsvuvj-ck.htmlthis

相關文章
相關標籤/搜索