1. 程式人生 > >vue-cli構建的專案中使用svg圖示

vue-cli構建的專案中使用svg圖示

1、安裝外掛:

npm i -S svg-sprite-loader

2、更改build/webpack.base.conf.js配置檔案

        {
            test: /\.svg$/,
            loader: 'svg-sprite-loader',
            include: [path.resolve(__dirname, '../src/images/icons')],
            options: {
                //symbolId: 'icon-[name]' //這個沒有生效,生效的是預設的name
            }
        }
        {
            test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
            loader: 'url',
            exclude: [path.resolve(__dirname,'../src/images/icons')], //排除字型圖示檔案
            query: {
                limit: 10000,
                name: utils.assetsPath('img/[name].[ext]')
            }
        },

3、下載svg檔案並放入images/icons/svg/目錄下,

4、新建公用元件components/common/SvgIcon.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 `#${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>

5、新建src/images/icons/index.js檔案

import Vue from 'vue'
import SvgIcon from '../../components/common/SvgIcon'
/* require.context("./test", false, /.test.js$/);
    這行程式碼就會去 test 資料夾(不包含子目錄) 下面的找所有檔名以 .test.js 結尾的檔案能被 require 的檔案。
    更直白的說就是 我們可以通過正則匹配引入相應的檔案模組。
     require.context有三個引數: 
     directory:說明需要檢索的目錄 
     useSubdirectories:是否檢索子目錄 
     regExp: 匹配檔案的正則表示式 */
//全域性註冊 
Vue.component('svg-icon', SvgIcon) 
const requireAll = requireContext => requireContext.keys().map(requireContext) 
const req = require.context('./svg', false, /\.svg$/) 
requireAll(req)

6、main.js中引入元件

import './images/icons/index.js'

7、元件中應用

<svg-icon icon-class="location"></svg-icon>
<svg-icon icon-class="search"></svg-icon>