组件自定义
props
props传入数据。
$emit
this.$emit(“input”,param);调用组件外部的监听。
v-model
自定义组件要使用v-model实现双向绑定,会使用名称为value的props,和名称为input的事件。下面有实现。
下拉框实现代码
/* 自定义下拉列表组件样式 */
.custom-select-box{
min-height: 30px;
width: 100%;
position: relative;
}
.custom-select-box .show-box{
display: flex;
justify-content: space-between;
align-items: center;
height: 30px;
width: 100%;
border: 1px solid #ffffff30;
border-radius: 5px;
background: #4A5564;
padding:0 8px;
cursor: pointer;
}
.custom-select-box .show-box.selecting{
border: 1px solid #00D9FFFF;
}
.custom-select-box .show-box .arrow-down{
width: 14px;
height: 17px;
transform:rotate(90deg);
background-image: url("../images/right-arrow.png");
}
.custom-select-box .show-box .arrow-right{
width: 14px;
height: 17px;
background-image: url("../images/right-arrow.png");
}
.custom-select-box .dropdown-box{
position: absolute;
border-radius: 5px;
top: 32px;
width: 100%;
height: auto;
max-height: 120px;
overflow-y: auto;
overflow-x: hidden;
background: #fdfdfd;
}
.custom-select-box .dropdown-box::-webkit-scrollbar {
width: 3px;
}
.custom-select-box .dropdown-box::-webkit-scrollbar-thumb {
background: rgba(0, 213, 255 , 0.7);
}
.custom-select-box .dropdown-box::-webkit-scrollbar-track {
background: rgba(0, 213, 255, 0.1);
}
.custom-select-box .dropdown-box .dropdown-item{
position: relative;
height: 30px;
width: 100%;
color: #0C0C0C;
padding: 0 8px;
line-height: 30px;
}
.custom-select-box .dropdown-box .dropdown-item:hover{
color: #0C0C0C;
background: rgba(0, 213, 255, 0.4);
cursor: pointer;
}
Vue.component("custom-select-box", {
props: {
list: Array,
value: String,
tabindex: Number
},
template: `
<div class="custom-select-box" :tabindex="tabindex?tabindex:1000" @blur="selecting = false">
<div @click="selecting=!selecting" :class="['show-box',selecting?'selecting':'']" >
<div>{{label}}</div>
<div class="arrow-down"></div>
</div>
<ul v-show="selecting" class="dropdown-box" >
<li class="dropdown-item" v-for="item in listItems"
@click="searchValueHandle(item)">{{item.label}}</li>
</ul>
</div>`,
methods: {
searchValueHandle(item) {
this.$emit("input", item.value);
this.selecting = false;
}
},
data:function(){
return {
selecting:false
}
},
computed:{
currentItem:function(){
return this.list ? this.list.find(x=>x.value===this.value):null;
},
label:function(){
return this.currentItem ? this.currentItem.label : "未选择";
},
listItems:function(){
if(this.list && this.list.length>0){
//做传入参数转换
return this.list.map(function(item){
if(typeof item ==='string'){
return {
value:item,
label:item
}
}else{
return item;
}
});
}
return [];
}
}
});
组件使用
<custom-select-box style="z-index: 5" v-model="testvalue" :list="[]" ></custom-select-box>
注意点
- tabindex 使得div元素可以触发blur事件。
- 有多个下拉框在同一个页面时,需要添加z-index,不然,先加的组件的下拉框会被后加的遮挡。