<template>
<el-select
ref="colorSelect"
placeholder=""
v-model="myColor"
style="width: 100%"
@change="handleChange"
>
<el-option
v-for="item in colorList"
:key="item"
label=" "
:value="item"
v-html="
'<div class=se style=background-color:' +
item +
';width:30px;border-radius:3px;display:inline-block;height:' +
'90%' +
'><span style=margin-left:40px;>颜色</span></div>'
"
>
</el-option>
</el-select>
</template>
<script>
export default {
name: "colorSelect",
//允许一个自定义组件在使用 v-model 时定制 prop 和 event。默认情况下,一个组件上的 v-model 会把 value 用作 prop 且把 input 用作 event,
//但是一些输入类型比如单选框和复选框按钮可能想使用 value prop 来达到不同的目的。使用 model 选项可以回避这些情况产生的冲突。
model: {
prop: "color",
event: "update",
},
props: {
//颜色数组
colorList: {
type: Array,
default: () => {
return ["#FFC0CB", "#DB7093", "#FF1493", "#DC143C"];
},
},
//父组件绑定的值
color: {
type: String,
default: undefined,
},
},
data() {
return {
myColor: undefined,
};
},
methods: {
//设置颜色选择框中颜色
setSelectColor(color) {
//通过操作dom节点改变样式
this.$nextTick(() => {
let dom = this.$refs.colorSelect;
if (dom) {
dom = dom.$el.children[0];
let inputDom = dom.querySelectorAll(".el-input__inner");
let icon = dom.querySelectorAll(".el-input__icon");
inputDom[0].style["padding-left"] = "43px";
icon[0].style["color"] = "black";
// 已选择的色块
var li = document.createElement("div");
li.className = "sekuai";
inputDom[0].value = "红色";
dom.querySelectorAll(".el-input__suffix")[0].appendChild(li);
dom.querySelectorAll(".sekuai")[0].style["background"] = color;
}
});
},
handleChange(val) {
this.setSelectColor(val);
//触发update事件更新父组件绑定值
this.$emit("update", val);
},
},
created() {
if (this.color && this.color.length > 0) {
this.myColor = this.color;
this.setSelectColor(this.color);
}
},
watch: {
color: function (val) {
this.setSelectColor(val);
},
},
};
</script>
<style scoped>
.se {
display: inline-block;
}
</style>
这里有用到v-html:可以切换内部html元素
v-text的话只能切换内部文字
import colorSelect from "../../commonview/colorSelect.vue";
components: {
colorSelect
}
<color-select :color-list="colorList" v-model="color"></color-select>
data(){
//颜色初始数据
colorList: ["#FFC0CB", "#DB7093", "#FF1493", "#DC143C",
"#DDA0DD", "#DA70D6", "#FF00FF", "#9370DB",
"#800080", "#6495ED", "#4169E1", "#0000FF",
"#87CEEB", "#E1FFFF", "#00FFFF", "#7FFFAA",
"#00FF7F", "#008000", "#FFFFE0", "#FFFF00",
"#FFD700", "#F5DEB3", "#FFA500", "#CD5C5C"],
//可设置默认值
color:'#FFC0CB'
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_52691965/article/details/126037224
内容来源于网络,如有侵权,请联系作者删除!