vue 自己实现select
<template>
<div class="form">
<span class="label">{{ label }}</span>
<input
contenteditable="true"
class="input"
:value="getLabel()"
@input="handleInput"
readonly="readonly"
@focus.stop="showOptions = true"
@blur.stop="showOptions = false"
/>
<div></div>
<div class="options" v-show="showOptions">
<div
class="option"
@mousedown="optionClick(item)"
v-for="(item, index) in options"
>
{{ item.label }}
</div>
<div class="bottom">
<slot></slot>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showOptions: false,
};
},
props: {
value: {
type: String,
default: "",
},
label: {
type: String,
default: "",
},
options: {
type: Array,
default: [],
},
},
methods: {
getLabel() {
let p = null;
console.log(this.options);
this.options.forEach((elem, index) => {
if (elem.value == this.value) {
p = elem.label;
}
});
return p;
},
optionClick(v) {
this.$emit("input", v.value);
this.showOptions = false;
this.$emit("optionClick", v);
},
handleInput(e) {
// this.$emit("input", e.target.value);
},
},
};
</script>
<style lang="scss" scoped>
.form {
display: inline-block;
line-height: 40px;
vertical-align: middle;
margin-right: 10px;
margin-bottom: 5px;
position: relative;
.label {
display: inline-block;
background-color: #009933;
height: 40px;
padding: 0 10px;
color: #fff;
border: 0px solid #a7a7a7;
vertical-align: middle;
border-radius: 5px 0 0 5px;
}
.input {
width: 200px;
display: inline-block;
height: 40px;
padding: 0 10px;
vertical-align: middle;
border: 0px solid #a7a7a7;
border-left: 0px;
outline: 0px solid #afecab;
border-radius: 0 5px 5px 0;
&:focus {
outline: 2px solid #009933;
}
}
.input::after {
content: "as";
width: 100px;
height: 20px;
background: #ebeef5;
display: block;
position: absolute;
left: 22%;
bottom: 0px;
z-index: 2;
}
.options {
border: 2px solid #009933;
border-radius: 5px;
width: 200px;
position: absolute;
right: 0;
top: 42px;
background-color: #ebebeb;
.option {
margin: 2px 0;
padding: 0px 10px;
line-height: 20px;
cursor: pointer;
&:hover {
color: rgb(61, 192, 21);
background-color: rgb(235, 255, 243);
}
}
}
.bottom {
border-top: 1px solid #a7a7a7;
}
}
</style>