近日项目中用到了一个多选效果想用字体图标实现,记录一下,效果图如下:选中的为蓝色,传值为‘1’,未选中为灰色,传值为‘0’
主要代码如下:
<div class="sheshi">
<div class="sheshi-con" v-for="(item, index) in items" :key="index" @click="toggleSelection(item)"
:class="{ 'selected': item.isSelected }">
<div class="sheshi-img">
<i :class="['iconfont', item.icon, { 'blue': item.isSelected }]"></i>
</div>
<div class="sheshi-ti" :class="{ 'blue': item.isSelected }">{{ item.title }}</div>
</div>
<button @click="sendDataToBackend">发送数据到后台</button>
</div>
const items = ref([
{ icon: 'icon-jingjichang', title: '月台', prop: 'platformFlag', isSelected: false, value: '0' },
{ icon: 'icon-dianti', title: '货梯', prop: 'liftFlag',isSelected: false, value: '0' },
{ icon: 'icon-shangxialou', title: '坡道', prop: 'rampFlag', isSelected: false, value: '0' },
{ icon: 'icon-shangxialou', title: '斜坡', prop: 'slopeFlag', isSelected: false, value: '0' },
{ icon: 'icon-miehuoqi', title: '消防设备', prop: 'fireFlag', isSelected: false, value: '0' },
{ icon: 'icon-yeying', title: '雨棚', prop: 'awningFlag',isSelected: false, value: '0' },
{ icon: 'icon-shangpin', title: '单面卸货', prop: 'singleFlag',isSelected: false, value: '0' }
])
const toggleSelection = (item) => {
item.isSelected = !item.isSelected;
item.value = item.isSelected ? '1' : '0';
}
.sheshi {
display: flex;
margin-top: 25px;
margin-bottom: 30px;
justify-content: space-between;
.sheshi-con {
cursor: pointer;
.sheshi-img {
width: 60px;
padding: 12px;
background-color: #f7fafc;
border-radius: 50%;
}
.iconfont {
font-size: 36px;
color: #999;
}
.sheshi-ti {
width: 60px;
color: #999;
font-size: 12px;
font-weight: 400;
padding-top: 8px;
text-align: center;
}
.sheshi-img i.blue {
color: #000;
/* 选中后的蓝色 */
}
.sheshi-ti.blue {
color:#000;
/* 选中后的蓝色 */
}
}
}
提交的时候处理数据
const dataToSend = items.value.map(item => ({ prop: item.prop, value: item.value }))
dataToSend.forEach(item=>{
form.value[item.prop] = item.value
})
编辑的时候反显数据,处理图标反显逻辑:
// 根据form的值更新items中每个项目的value
for (const item of items.value) {
if (form.value.hasOwnProperty(item.prop)) {
item.value = form.value[item.prop];
item.isSelected = form.value[item.prop] === '1';
}
}