vue实现icon多选组件
实现思路
通过封装一个支持多选的图标选择器组件,利用 Vue 的响应式特性管理选中状态,结合图标库(如 Font Awesome、Element UI 图标)渲染可选项,并暴露选中数据供父组件使用。
![]()
核心代码实现
图标数据配置
假设使用 Element UI 的图标库,预先定义图标列表:
// iconList.js
export const iconList = [
'el-icon-platform-eleme',
'el-icon-delete-solid',
'el-icon-setting',
'el-icon-user-solid',
// 更多图标...
];
组件模板
<template>
<div class="icon-selector">
<div
v-for="icon in icons"
:key="icon"
class="icon-item"
:class="{ 'selected': selectedIcons.includes(icon) }"
@click="toggleIcon(icon)"
>
<i :class="icon"></i>
</div>
</div>
</template>
组件逻辑
<script>
import { iconList } from './iconList';
export default {
props: {
value: { type: Array, default: () => [] } // 接收父组件 v-model 绑定的数组
},
data() {
return {
icons: iconList,
selectedIcons: [...this.value] // 初始化选中状态
};
},
methods: {
toggleIcon(icon) {
const index = this.selectedIcons.indexOf(icon);
if (index === -1) {
this.selectedIcons.push(icon);
} else {
this.selectedIcons.splice(index, 1);
}
this.$emit('input', [...this.selectedIcons]); // 更新父组件绑定值
}
},
watch: {
value(newVal) {
this.selectedIcons = [...newVal]; // 同步外部数据变化
}
}
};
</script>
样式增强
<style scoped>
.icon-selector {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.icon-item {
padding: 8px;
cursor: pointer;
border: 1px solid #ddd;
border-radius: 4px;
}
.icon-item:hover {
background-color: #f5f5f5;
}
.icon-item.selected {
border-color: #409eff;
background-color: #ecf5ff;
}
</style>
使用示例
父组件中引入并绑定数据:
<template>
<icon-selector v-model="selectedIcons" />
<p>已选图标:{{ selectedIcons.join(', ') }}</p>
</template>
<script>
import IconSelector from './IconSelector.vue';
export default {
components: { IconSelector },
data() {
return {
selectedIcons: []
};
}
};
</script>
关键点说明
- 双向绑定:通过
v-model实现父子组件数据同步,利用value属性和input事件。 - 性能优化:图标较多时可考虑虚拟滚动(如
vue-virtual-scroller)。 - 自定义图标库:替换
iconList数据即可适配其他图标库(如 Font Awesome、Iconfont)。 - 多选逻辑:通过数组的
includes和splice方法实现选中/取消选中。
![]()






