vue实现icon多选组件
Vue 实现 Icon 多选组件
组件设计思路
多选 Icon 组件的核心在于管理选中状态和渲染可交互的图标列表。通常需要以下功能:
- 支持传入图标列表(本地或远程)
- 支持单选/多选模式
- 提供选中状态的回调事件
- 支持自定义样式
基础实现代码
<template>
<div class="icon-selector">
<div
v-for="icon in icons"
:key="icon.name"
class="icon-item"
:class="{ 'selected': selectedIcons.includes(icon.name) }"
@click="toggleSelect(icon)"
>
<i :class="icon.class"></i>
<span>{{ icon.name }}</span>
</div>
</div>
</template>
<script>
export default {
props: {
icons: {
type: Array,
required: true
},
multiple: {
type: Boolean,
default: true
}
},
data() {
return {
selectedIcons: []
}
},
methods: {
toggleSelect(icon) {
if (this.multiple) {
const index = this.selectedIcons.indexOf(icon.name)
index === -1
? this.selectedIcons.push(icon.name)
: this.selectedIcons.splice(index, 1)
} else {
this.selectedIcons = [icon.name]
}
this.$emit('change', this.selectedIcons)
}
}
}
</script>
<style scoped>
.icon-selector {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.icon-item {
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
cursor: pointer;
display: flex;
flex-direction: column;
align-items: center;
}
.icon-item:hover {
background-color: #f5f5f5;
}
.icon-item.selected {
border-color: #409eff;
background-color: #ecf5ff;
}
</style>
使用 Font Awesome 示例
// 父组件中使用
<template>
<icon-selector
:icons="faIcons"
@change="handleIconChange"
/>
</template>
<script>
import IconSelector from './IconSelector.vue'
export default {
components: { IconSelector },
data() {
return {
faIcons: [
{ name: 'home', class: 'fas fa-home' },
{ name: 'user', class: 'fas fa-user' },
{ name: 'cog', class: 'fas fa-cog' },
{ name: 'bell', class: 'fas fa-bell' }
]
}
},
methods: {
handleIconChange(selected) {
console.log('Selected icons:', selected)
}
}
}
</script>
高级功能扩展
搜索过滤
<input
v-model="searchQuery"
placeholder="Search icons..."
class="search-input"
>
// 计算属性
computed: {
filteredIcons() {
return this.icons.filter(icon =>
icon.name.includes(this.searchQuery.toLowerCase())
)
}
}
分类显示
// 数据结构
icons: [
{
category: 'Common',
items: [
{ name: 'home', class: 'fas fa-home' },
{ name: 'user', class: 'fas fa-user' }
]
}
]
// 模板修改
<div v-for="group in icons" :key="group.category">
<h4>{{ group.category }}</h4>
<div class="icon-group">
<div v-for="icon in group.items" ...>
<!-- 原有图标渲染 -->
</div>
</div>
</div>
性能优化
对于大量图标的情况:
- 使用虚拟滚动(vue-virtual-scroller)
- 实现懒加载
- 分页显示
- 防抖搜索
import { debounce } from 'lodash'
methods: {
search: debounce(function(query) {
this.searchQuery = query
}, 300)
}
注意事项
- 图标库需要提前引入(如 Font Awesome)
- 选中状态可持久化到 Vuex 或 localStorage
- 移动端需增加触摸反馈
- 考虑无障碍访问(ARIA 属性)
![]()






