element-ui制作多颜色选择器
将颜色存储到一个数组中去。
<template>
<div class="color-picker-container" style="margin-top: 10px;">
<!-- 显示已选颜色 -->
<div class="color-selection">
<div
v-for="(color, index) in selectedColors"
:key="index"
class="color-chip"
:style="{ backgroundColor: color }"
>
<button @click="removeColor(index)" class="remove-btn">X</button>
</div>
<!-- 颜色选择器 -->
<el-color-picker
v-if="showColorPicker"
v-model="currentColor"
@change="addColor"
show-alpha
size="small"
class="color-picker"
/>
<div v-if="selectedColors.length < maxColors" class="add-color-btn" @click="showColorPicker = !showColorPicker">
+
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedColors: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#7265E6', '#EBEEF5'], // 默认6个颜色
currentColor: null,
showColorPicker: false,
maxColors: 10 // 最大可选颜色数量
};
},
methods: {
addColor(color) {
if (color && this.selectedColors.length < this.maxColors && !this.selectedColors.includes(color)) {
this.selectedColors.push(color);
}
this.showColorPicker = false;
},
removeColor(index) {
this.selectedColors.splice(index, 1);
},
},
};
</script>
<style scoped>
.color-picker-container {
position: relative;
}
.color-selection {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 16px;
}
.color-chip {
width: 40px;
height: 40px;
border-radius: 8px; /* 圆角 */
position: relative;
cursor: pointer;
transition: transform 0.1s ease-in-out;
}
.color-chip:hover {
transform: scale(1.1); /* 悬停时放大 */
}
.remove-btn {
position: absolute;
top: -6px;
right: -6px;
background-color: white;
border: 1px solid #ccc;
border-radius: 50%;
width: 16px;
height: 16px;
line-height: 14px;
text-align: center;
font-size: 10px;
cursor: pointer;
display: none;
}
.color-chip:hover .remove-btn {
display: block;
}
.add-color-btn {
width: 40px;
height: 40px;
border-radius: 8px; /* 圆角 */
background-color: #f0f0f0;
border: 1px dashed #dcdcdc;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
color: #8c8c8c;
cursor: pointer;
transition: background-color 0.3s ease;
}
.add-color-btn:hover {
background-color: #e0e0e0;
}
.color-picker {
/*position: absolute;*/
bottom: -5px;
left: 0;
}
</style>