Vue.js 图标选择组件实践详解

2020-06-14 06:00:08易采站长站整理

<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></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,这里是所有组件的集合