本篇文章是在 vue-cli 腳手架項目環(huán)境下講解
svg-sprite-loader 將加載的 svg 圖片拼接成 雪碧圖,放到頁面中肪笋,其它地方通過 <use> 復(fù)用
首先在 src 下建立以下目錄和文件:
安裝和配置 svg-sprite-loader:
安裝:
npm i -D svg-sprite-loader
webpack 配置:
{
test: /\.svg$/,
loader: 'svg-sprite-loader',
include: [resolve('src/icons')],
options: {
symbolId: 'icon-[name]'
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
},
exclude: [resolve('src/icons')]
},
注意 url-loader 中要將 icons 文件夾排除, 不讓 url-loader 處理該文件夾
components 中新建組件 SvgIcon.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>
icons 下面的 index.js 寫入以下內(nèi)容:
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg組件
// register globally
Vue.component('svg-icon', SvgIcon)
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)
入口 main.js 將 index.js 引入:
import '@/icons'
然后 就可以使用了:
前面已經(jīng)全局注冊了月劈,所以可以直接使用
<svg-icon icon-class="eye"></svg-icon>
- icon-class 的值是 svg 文件名
eye.svg
-
原理:
查看頁面,svg-sprite-loader 將 svg 文件內(nèi)容放到了 body 下面:
歡迎關(guān)注R照弧S⒘搿湾盒!順便下面點個贊唄~