[Vuejs] svg-sprite-loader實現加載svg自定義組件

一、安裝 svg-sprite-loadervue

npm install svg-sprite-loader -D

或者webpack

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

二、將全部svg圖片放到assets/svg下,以此爲例,修改文件 build/webpack.base.conf.jsweb

找到代碼:npm

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

增長一行 ecmascript

exclude: [resolve("src/assets/svg")],svg

意思是用url-loader加載的時候過濾掉文件夾 src/assets/svg 下面的文件ui

this

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

同時在後面增長一條規則url

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

三、自定義SvgIcon組件spa

在components新建 SvgIcon.vue

<template>
  <svg :class="svgClass" :style="style" aria-hidden="true">
    <use :xlink:href="`#${name}`"></use>
  </svg>
</template>

<script type="text/ecmascript-6">
export default {
  name: 'svg-icon',
  props: {
    name: {
      type: String,
      required: true
    },
    className: {
      type: String
    },
    width: {
      type: String,
      default: '5vw'
    },
    height: {
      type: String,
      default: '5vw'
    }
  },
  data () {
    return {
      style: {
        width: this.width,
        height: this.height
      }
    }
  },
  computed: {
    svgClass () {
      if (this.className) {
        return 'svg-icon ' + this.className
      } else {
        return 'svg-icon'
      }
    }
  }
}
</script>

<style>
.svg-icon {
  width: 5vw;
  height: 5vw;
  fill: currentColor;
  overflow: hidden;
}
</style>

其中綁定了class和style,在用這個組件的時候能夠直接設置寬度和高度以及類名,額外的屬性能夠本身擴展。

四、建立svg.js用於註冊SvgIcon組件和批量引入svg圖片,我建立在src/utils/svg.js

import Vue from 'vue'
import SvgIcon from '../components/SvgIcon.vue'

Vue.component('svg-icon', SvgIcon)

// 引入全部svg
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('../assets/svg', false, /\.svg$/)
// const iconMap = requireAll(req)
// console.log(iconMap)
requireAll(req)

五、用法

<svg-icon name="icon-pc" width="12vw" height="12vw"></svg-icon>

name值即爲svg圖片名稱,如上icon-pc,即爲icon-pc.svg

相關文章
相關標籤/搜索