1.在src/ 下面新建目錄icons,里面新建文件夾svg,和文件index.js 。svg用於存放從iconfont下載下來的svg格式的圖標,index.js用於引入使用到svg文件和對應的組件。
import Vue from 'vue' import SvgIcon from '@/components/SvgIcon'// 自定義的svg組件 // register globally Vue.component('svg-icon', SvgIcon)//在vue中全局引入圖標組件
//引入所有的svg組件 const requireAll = requireContext => requireContext.keys().map(requireContext) const req = require.context('./svg', false, /\.svg$/) const iconMap = requireAll(req)
注意:“ require.context('./svg', false, /\.svg$/) ”表示引入 svg目錄下的所有svg文件。 引入svg文件時,引入的文件路徑要和實際路徑保持一致
2.vue編譯svg文件默認使用的是 url-loader ,我們需要安裝 svg-sprite-loader 進行處理;
npm install svg-sprite-loader --save-dev
再在 " \build\webpack.base.conf.js " 里面修改編譯loader
{ test: /\.svg$/, loader: 'svg-sprite-loader', include: [resolve('src/icons')],//只有src/icons下的svg使用svg-sprite-loader編譯 options: { //編譯時把svg的文件名前添加上icon,方便使用 symbolId: 'icon-[name]' } }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', exclude: [resolve('src/icons')],//src/icons下的svg文件都不使用url-loader編譯 options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } },
3.新建字體圖標組件,方便引用。“ src\components\SvgIcon\index.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 `#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官網引用方式定義的組件,注意 “ :xlink:href="iconName" ”中的名稱要和引入的svg文件名稱一致。我們前面在webpack.base.conf.js中引用文件時添加了“ #icon- ” ,所以組件中的iconName也要添加“ #icon- ”,“ #icon- ”后面的名稱要和引入的圖標文件名一致。
4.使用svg圖標。在頁面中引用圖標,只需要調用剛剛定義的組件就行。該組件我們前面在index,js中已經全局引入過了
<svg-icon icon-class="404" class-name="svg-404"></svg-icon>
上面的404圖標就需要在 “ src/icons/svg/404.svg ” 下有對應的文件, “svg-404”是自定義的組件的樣式。