github地址 https://github.com/miaolianfen/vue-demo
歡迎給個小星星灸叼,哈哈
一、安裝
首先先安裝svg-sprite-loader
npm i svg-sprite-loader -D
二、創(chuàng)建存放svg的文件夾
在項(xiàng)目的src文件下創(chuàng)建icons/svg文件夾,此文件夾專門用來存放icons的小圖標(biāo),將來會從該文件夾中讀取所有的icons圖標(biāo)
三. 修改規(guī)則和新增規(guī)則
在vue-cli3中默認(rèn)已經(jīng)配了對svg處理的規(guī)則(見下圖)
image.png
所以在vue.config.js里擴(kuò)展webpack的配置辖佣,首先要排除file-loader對我們icons文件夾的處理,然后利用svg-sprite-loader對icons文件夾的進(jìn)行專門的處理
const path=require('path')
// resolve定義一個絕對路徑獲取函數(shù)
function resolve(dir){
return path.join(__dirname,dir)
}
module.exports = {
chainWebpack(config){
//排除icons目錄中svg文件處理
config.module.rule('svg')
.exclude.add(resolve('src/icons'))
.end()
//設(shè)置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()
}
}
四. 創(chuàng)建svg-icon組件
<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>
五. 圖標(biāo)自動導(dǎo)入并全局引用組件
在icons文件下下面創(chuàng)建index.js文件搓逾,來做上面創(chuàng)建的組件的全局注冊和自動導(dǎo)入svg文件夾下面所有的svg圖標(biāo)
// 全局引入SvgIcon組件
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon.vue'
Vue.component('svg-icon', SvgIcon)
// 設(shè)置icons/svg下面的圖片自動導(dǎo)入
const req = require.context('./svg', false, /\.svg$/);
req.keys().map(req);
最后不要忘了在main.js 中引用icons/index.js
六. 使用
使用方法如下:
<svg-icon icon-class="home"></svg-icon>
github地址 https://github.com/miaolianfen/vue-demo
轉(zhuǎn)載請作說明
歡迎給個小星星卷谈,哈哈