首先队贱,這是一篇摘抄筆記,具體使用原理等更詳細的內(nèi)容潭袱,請參考原作者的 手摸手露筒,帶你優(yōu)雅的使用 icon 。
想要更優(yōu)雅(偷懶)的在項目中使用svg圖標敌卓,肯定能想到的就是封裝組件慎式,但是光封裝組件是不行滴,你還需要:
- 創(chuàng)建結(jié)構(gòu)文件
src/components/SvgIcon/index.vue // 圖標組件文件
<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>
src/icons/index.js // 處理svg文件夾中svg圖標趟径,并在Vue上注冊全局組件
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon' // svg組件
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
src/icons/svg // svg圖標文件存放文件夾瘪吏,所有下載的svg圖標全部放在這個文件中
-
使用 svg-sprite并配置config文件
npm install svg-sprite-loader -D # via yarn yarn add svg-sprite-loader -D
配置webpack.base.conf.js中的規(guī)則
{ ...其他代碼省略 module: { rules: [ ...其他代碼省略 { // 這個花括號中都是新增的規(guī)則 test: /\.svg$/, loader: 'svg-sprite-loader', include: [path.resolve(__dirname, "../src/icons")], // 確保這個路徑正確 options: { symbolId: 'icon-[name]' } }, { // 這個規(guī)則中新增了exclude這一行 test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, exclude: [path.resolve(__dirname, "../src/icons")], // 確保這個路徑正確 use: { loader: 'url-loader', query: { limit: 10000, name: 'imgs/[name]--[folder].[ext]' } } } ] } }
最后就可以在其他組件中愉快的使用了:<svg-icon icon-class="star"/>