vuecli3.0 優雅使用svg


1:vue-cli對svg文件有默認的url-loader 處理,我們要使用svg 圖標需單獨進行配置

下載一個插件svg-sprite-loader來單獨處理我們的svg圖標,它是一個webpack loader,支持將多個svg打包成svg sprites

npm install svg-sprite-loader -D

2:vue.config.js

// 內置路徑包const path = require("path");
// 定義resolve方法,獲取絕對路徑function resolve(dir) { return path.join(__dirname, dir);}
module.exports = {
// 一個函數,會接收一個基於 webpack-chain 的 ChainableConfig 實例

// 允許對內部的 webpack 配置進行更細粒度的修改

chainWebpack: config => {

// 配置svg默認規則排除icons目錄中svg文件處理

config.module

  .rule("svg")

  .exclude.add(resolve("src/icons"))

  .end();

// 新增icons規則,設置svg-sprite-loader處理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]" })

  .end();

}
}

 




3 const req = require.context("./svg", false, /\.svg$/);
req.keys().map(req);

4:components/目錄下新建SvgIcon/index.vue文件,我們寫一個svgicon組件,封裝一下再全局注冊,這樣使用起來就會很方便了!

<template>
  <svg :class="svgClass" aria-hidden="true" v-on="$listeners">
    <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>
 
5 在 icon/index

import Vue from "vue";
import SvgIcon from "@/components/SvgIcon";

// icons圖標自動加載
const req = require.context("./svg", false, /\.svg$/);
req.keys().map(req);

// 全局注冊svg-icon組件
Vue.component("svg-icon", SvgIcon);
 
          
6:import "@/icons/index.js";

7:頁面使用
<template>
  <svg-icon icon-class="qq" class-name="qq-style"></svg-icon>
</template>
 


免責聲明!

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



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