svgicon組件使用方法示例詳解
場景
最近在研發(fā)產(chǎn)品的過程中,ued切了很多svg的圖片;咱們在使用過程中除了背景圖再就是使用<img :src="url"/>進行使用。
在你進行公共組件編寫的時候,使用圖片路徑這種方式編寫完組件發(fā)布之后;在再項目中引入已發(fā)布的組件,在你運行代碼的時候圖片路徑會附帶上當(dāng)前運行的域名,導(dǎo)致圖片顯示不出來。

那么怎么解決這種問題呢?
- 和UED進行溝通讓他們把這種svg的圖片做成icon;
- 前端自己完成svg轉(zhuǎn)換icon,封裝Svgicon可復(fù)用組件;減少溝通成本;提高復(fù)用率來提升研發(fā)效率。
我們選擇的是第二種方式使用svg-sprite-loader進行svg到icon的轉(zhuǎn)換
編寫SvgIcon組件
組件文件結(jié)構(gòu)
src/packages/SvgIcon/index.vue
//src/packages/SvgIcon/index.vue
<template>
<div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" />
<svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :href="iconName" rel="external nofollow" />
</svg>
</template>
<script>
import { isExternal } from '@/utils/validate'
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
computed: {
isExternal() {
return isExternal(this.iconClass)
},
iconName() {
return `#icon-${this.iconClass}`
},
svgClass() {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
},
styleExternalIcon() {
return {
mask: `url(${this.iconClass}) no-repeat 50% 50%`,
'-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover!important;
display: inline-block;
}
</style>
icons文件結(jié)構(gòu)
src/packages/icons
src/packages/icons/svg 該文件夾放置svg文件
src/packages/icons/index.js
/**src/packages/icons/index.js**/
import Vue from 'vue'
import SvgIcon from '../SvgIcon'// svg component
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
按照上面的步驟組件就編寫完了,可以進行發(fā)布使用;
具體使用方法如下。
<svg-icon icon-class="PaperSearch" style="font-size: 64px"></svg-icon>
該組件還需結(jié)合使用svg-sprite-loader進行使用
npm i svg-sprite-loader
vue.config.js配置
chainWebpack: (config) => {
config.module.rule('svg').exclude.add(resolve('src/packages/icons')).end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/packages/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
最終效果

以上就是svgicon組件使用方法示例詳解的詳細內(nèi)容,更多關(guān)于svgicon組件方法的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
微信小程序之MaterialDesign--input組件詳解
本篇文章主要介紹了微信小程序之MaterialDesign--input組件詳解,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-02-02
JavaScript?CSS優(yōu)雅實現(xiàn)網(wǎng)頁多主題風(fēng)格換膚功能詳解
這篇文章主要為大家介紹了JavaScript?CSS優(yōu)雅的實現(xiàn)網(wǎng)頁多主題風(fēng)格換膚功能詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02
微信小程序 頁面跳轉(zhuǎn)和數(shù)據(jù)傳遞實例詳解
這篇文章主要介紹了微信小程序 頁面跳轉(zhuǎn)和數(shù)據(jù)傳遞實例詳解的相關(guān)資料,這里附有實例代碼幫助到家學(xué)習(xí)理解,需要的朋友可以參考下2017-01-01

