需求是新建标签,并且带上颜色,项目用的是element ui组件库,自带的<el-color-picker>与需求不符,所以自定义了一个。
前言
老板发来的原型图是这样的
element ui里面的颜色选择器是这样的
因为每个人操作习惯不一样,后面可能会出现五颜六色的标签, 所以讨论了下,只限定一些颜色可设置。
一、思路
其实这种就自定义RadioButton的改版,只需要把数据换一下就行了
二、编码
1.定义颜色数组
predefineColors: {
options: [
{
text: '#F45B5A',
value: '#F45B5A',
},
{
text: '#FFCB45',
value: '#FFCB45',
},
{
text: '#FF8A4E',
value: '#FF8A4E',
},
{
text: '#6ABF40',
value: '#6ABF40',
},
{
text: '#3D96FF',
value: '#3D96FF',
},
{
text: '#00DAE0',
value: '#00DAE0',
},
{
text: '#5D5CDB',
value: '#5D5CDB',
},
{
text: '#B44D5F',
value: '#B44D5F',
},
{
text: '#c71585',
value: '#c71585',
},
],
},
2.通过颜色编码动态渲染item背景色
<div
v-for="(item, index) in radioObj.options"
:key="index"
:class="item.value === radioObj.value ? 'radio_style radio_check' : 'radio_style radio_uncheck'"
:style="{ background: item.text }"
@click="radioBtn(item)"
></div>
核心在这句
:style="{ background: item.text }"
3.通过getColor获取值
getColor(data) {
this.color = data
console.log('data: ', data)
},
三、使用
1.组件源码
ColorPicker.vue
<template>
<div class="container">
<div :span="18" class="row-radio-btn">
<div
v-for="(item, index) in radioObj.options"
:key="index"
:class="item.value === radioObj.value ? 'radio_style radio_check' : 'radio_style radio_uncheck'"
:style="{ background: item.text }"
@click="radioBtn(item)"
></div>
</div>
</div>
</template>
<script>
export default {
name: 'ColorPicker',
components: {},
props: {
color: {
type: String,
default: '#DA433C',
},
compsData: {
type: Object,
default: () => {
return {
label: '',
value: '',
options: [
{
text: '男',
value: '0',
},
{
text: '女',
value: '1',
},
],
}
},
},
},
data() {
return {
radioObj: {
options: [],
},
}
},
watch: {
compsData(data) {
this.radioObj = data
console.log('this.radioObj: ', this.radioObj)
},
color(newVal) {
this.color = newVal
this.radioBtn({ value: this.color })
},
},
mounted() {
this.radioObj = this.compsData
this.radioBtn({ value: this.color })
},
methods: {
radioBtn(item) {
this.radioObj.value = item.value
this.$emit('click', item.value)
},
},
}
</script>
<style lang="less" scoped>
.container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
background: #ffffff;
}
.title {
font-size: 14px;
color: #484848;
}
.row-radio-btn {
display: flex;
background: #ffffff;
flex-direction: row;
align-items: center;
justify-content: center;
height: 40px;
line-height: 40px;
}
.radio_style {
width: 15px;
margin-left: 10px;
height: 15px;
border-radius: 4px;
}
.radio_uncheck {
color: #9f9f9f;
}
.radio_check {
color: #ffffff;
width: 18px;
height: 18px;
}
</style>
2.引用
<ColorPicker :compsData="predefineColors" @click="getColor" :color="color"></ColorPicker>
predefineColors定义在文章开头了。
总结
使用RadioButton组件举一反三。