背景
最近項目中在做一個自定義菜單需求,其中有一個爲菜單設置小圖標的功能,就是大家常見的左側菜單
設置圖標不難,方案就是字體圖標,可供使用的圖標庫也有很多,比如阿里巴巴的 Iconfont,以及 Fontaswsome 等,問題在於如何優雅的提供幾百個圖標供用戶選擇,而不需要開發去一個一個的寫標籤,也不需要一個個的去找圖標。
字體圖標庫 Fontawesome 方案
我們使用字體圖標的方式,一般是一個 <i class="iconfont icon-home"></i>
這樣的標籤,平常開發中用一些圖標都是用到一個寫一個,展示10個圖標,就要寫10個標籤。
在項目中本人使用的是 Fontawesome 圖標庫方案,使用它是因爲提供的可用圖標比較豐富,基本上不需要特意去找合適的圖標,直接把它的圖標庫下載過來,免費的有800多個。
這麼多圖標難道要一個一個手寫800多個 i
標籤嗎?三連拒絕!
Fontawesome 下載後的文件中提供一個 svg格式的精靈圖,這個非常人性化,用 VSCode 打開這個SVG文件
可以看到是熟悉的DOM,因爲SVG本質上就是一個XML,既然是DOM,那麼祭出JS大法吧,用瀏覽器打開這個SVG文件,在控制檯編寫如下代碼獲取所有的圖標名稱:
const nodeArray = Array.from(document.querySelectorAll('symbol'));
const names = nodeArray.map(item => item.id)
names.toString()
Icons組件
大牛可以忽略
拿到了所有圖標的 name 那就好辦了,一個數組循環唄。先別急着寫代碼,我們的目的是封裝成組件複用,那麼先創建一個 Icons 組件
提供一個篩選框,然後給一個事件即可
<template>
<div class="ui-fas">
<el-input v-model="name" @input.native="filterIcons" suffix-icon="el-icon-search" placeholder="請輸入圖標名稱"></el-input>
<ul class="fas-icon-list">
<li v-for="(item, index) in iconList" :key="index" @click="selectedIcon(item)">
<i class="fas" :class="['fa-' + item]" />
<span>{{item}}</span>
</li>
</ul>
</div>
</template>
<script>
import fontawesome from '@/extend/fontawesome/solid.js'
export default {
name: 'compIcons',
data () {
return {
name: '',
iconList: fontawesome
}
},
methods: {
filterIcons () {
if (this.name) {
this.iconList = this.iconList.filter(item => item.includes(this.name))
} else {
this.iconList = fontawesome
}
},
selectedIcon (name) {
this.$emit('selected', name)
},
reset () {
this.name = ''
this.iconList = fontawesome
}
}
}
</script>
先把拿到的所有圖標name放到一個 solid.js 文件中,輸出爲數組,在組件中引入,然後就是循環數組 iconList
,輸出i
標籤,Fontawesome 的使用方式是:<i class="fas fas-圖標name"></i>
。
篩選功能利用數組的 filter 方法,this.$emit('selected', name)
方式返回給父組件圖標名稱。
以上樣式都是利用Element UI 的 Popover、Input 組件實現
<el-form-item label="圖標:" >
<el-popover
placement="left-start"
width="540"
trigger="click"
@show="$refs.icons.reset()"
popper-class="popper-class">
<ui-icons ref="icons" @selected="selectedIcon" />
<el-input slot="reference" placeholder="請輸入內容" readonly v-model="form.menu_icon" style="cursor: pointer;">
<template slot="prepend"><i class="fas" :class="['fa-' + form.menu_icon]"></i></template>
</el-input>
</el-popover>
</el-form-item>
組件實現了,接下來就是引用,既可以直接到導入此組件引用,也可以掛載到全局進行使用,這裏說說掛載到全局使用的方式,因爲我的項目中所有的公共組件都是掛載到全局的方式使用。
在組件平級新建一個 index.js 文件
import IconsCompontent from './Icons.vue'
const Icons = {
install(Vue) {
Vue.component('ui-icons', IconsCompontent);
}
}
export default Icons;
第4行爲組件命名,此名稱決定了如何使用組件,這裏是ui-icons
,那麼使用的時候就是:
<ui-icons />
接着在項目 components 根目錄新建 index.js,這裏是所有組件的集合
最後一步是在 main.js 中註冊:
import CustomComponents from './components/index.js'
Object.keys(CustomComponents).forEach(key => Vue.use(CustomComponents[key]))
這樣就可以在項目中任意.vue
文件中以<ui-icons />
方式使用組件了。
後記
點擊圖標後要不要關閉圖標彈出層(Popover)呢?Popover 是需要鼠標點擊其他地方纔會隱藏的,選擇一個圖標後就關閉 Popover 呢,我的做法是:document.body.click()
。
selectedIcon (name) {
this.form.menu_icon = name
// document.body.click()
}
....完。