vue-cli3 項目svg圖批量引用


vue-cli3 svn 導入

安裝依賴

npm install svg-sprite-loader -D

查看webpack 自帶的規則

vue inspect --rule svg

修改規則和新增規則,vue.config.js

const path = require('path');
function resolve(dir) {
  return path.join(__dirname, dir)
}

module.exports = {  
  chainWebpack(config) {
    // 修改當前項目默認svg 配置,排除icons目錄
    config.module.rule('svg')
      .exclude.add(resolve('./src/icons'))
    // 新增一個 rule:添加icons 里面svg
    config.module.rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('./src/icons')).end()
      .use('svg-sprite-loader')
        .loader('svg-sprite-loader')
        .options({symbolId: 'icon-[name]'})
  }
}

注意:修改vue.config.js 是需要重新啟動的

創建icons/index.js
// icons/index.js
// webpack 創建一個以svg 目錄為上下文的require函數
import Vue from 'vue'
import SvgIcon from '@components/SvgIcon.vue'
// 注冊svg 組件
Vue.component(SvgIcon.name, SvgIcon)

const req=require.context('./svg',false,/\.svg$/)
req.keys().map(req);// keys() 會獲取所有svg 文件

然后我們將此文件引入到main文件中

創建SvgICon組件,components/SvgIcon.vue
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName"/>
  </svg>
</template>

<script>
export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ''
    }
  },
  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>

使用組件

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

icon-class 對應的名稱,就是我們在icons/svg存放的文件名稱

class-name 可以去修改當前圖表樣式


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM