前端开发实现自定义勾选/自定义样式,可复选,可取消勾选
基于后端返回数组实现多选、复选
以下代码基于vue2,如果有需要React/Vue3或者其他框架代码的,可以通过国内直连GPT4o进行代码转换,转换正确率99%
前端代码如下(直接拷贝到你的vue代码即可):
<!-- CustomCheckboxList.vue -->
<template>
<div class="checkbox-list">
<div
v-for="(item, index) in items"
:key="index"
class="checkbox-item"
@click="toggleItem(index)"
>
<div
class="custom-checkbox"
:style="{
'border-color': item.color,
'background-color': item.checked ? item.color : 'transparent'
}"
>
<span
v-if="item.checked"
class="checkmark"
>✓</span>
</div>
<span class="item-text">{{ item.text }}</span>
</div>
</div>
</template>
<script>
export default {
name: 'CustomCheckboxList',
data() {
return {
// 示例数据,实际使用时可以通过 props 传入
items: [
{ text: '选项1', color: '#FF5733', checked: false },
{ text: '选项2', color: '#33FF57', checked: false },
{ text: '选项3', color: '#3357FF', checked: false },
{ text: '选项4', color: '#FF33F5', checked: false }
]
}
},
methods: {
toggleItem(index) {
this.$set(this.items[index], 'checked', !this.items[index].checked)
// 触发事件通知父组件选中状态变化
this.$emit('change', {
index,
checked: this.items[index].checked,
items: this.items
})
}
}
}
</script>
<style scoped>
.checkbox-list {
padding: 16px;
}
.checkbox-item {
display: flex;
align-items: center;
margin-bottom: 12px;
cursor: pointer;
}
.custom-checkbox {
width: 24px;
height: 24px;
border: 2px solid;
border-radius: 50%;
margin-right: 12px;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
}
.checkmark {
color: white;
font-size: 16px;
font-weight: bold;
}
.item-text {
font-size: 16px;
}
/* 可选的悬停效果 */
.checkbox-item:hover .custom-checkbox {
opacity: 0.8;
}
</style>