Skip to content

Instantly share code, notes, and snippets.

@edwardlorilla
Created June 8, 2021 16:16
Show Gist options
  • Save edwardlorilla/8a1039d794b1d9a50f2ae12a19a48e74 to your computer and use it in GitHub Desktop.
Save edwardlorilla/8a1039d794b1d9a50f2ae12a19a48e74 to your computer and use it in GitHub Desktop.
vue custom drop-down list
<template id="DropList">
<div class="zq-drop-list" @mouseover="onDplOver($event)" @mouseout="onDplOut($event)">
<span>{{dplLable}}</span>
<ul :style="{'display': unorderlist?'block':'none'}">
<li v-for="(item, index) in datalist" :key="index" @click="onLiClick(index, $event)">{{item[labelproperty]}}</li>
</ul>
</div>
</template>
<div id="app">
<div class="home">
<droplist :datalist="dplist" labelproperty="name" @change="onDpChange($event)"></droplist>
<p>Other text content</p>
</div>
</div>
Vue.component('droplist', {
template:'#DropList',
data(){
return {
activeIndex:0,
unorderlist: false
}
},
props:{
datalist:{
type:Array,
default(){
return [
{name: "Option Two"}
]
}
},
labelproperty:{
type:String,
default(){ return "name"}
}
},
methods:{
onDplOver(event){
this.unorderlist = true
},
onDplOut(event){
this.unorderlist = false
},
onLiClick(index){
let path = event.path || (event.composedPath && event.composedPath()) //Compatible with Firefox and safari
path[1].style.display = "none";
this.activeIndex = index;
this.$emit("change", {
index:index,
value:this.datalist[index]
})
}
},
computed:{
dplLable(){
return this.datalist[this.activeIndex][this.labelproperty]
}
}
})
new Vue({
data(){
return{
dplist: [
{name: "Option One"},
{name: "Option Two"}
]
}
},
methods:{
onDpChange(event){
console.log(event)
}
}
}).$mount('#app')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
.zq-drop-list{
display: inline-block;
min-width: 100px;
position: relative;
span{
display: block;
height: 30px;
line-height: 30px;
background: #f1f1f1;
font-size: 14px;
text-align: center;
color: #333333;
border-radius: 4px;
}
ul{
position: absolute;
top: 30px;
left: 0;
width: 100%;
margin: 0;
padding: 0;
border: solid 1px #f1f1f1;
border-radius: 4px;
overflow: hidden;
li{
list-style: none;
height: 30px;
line-height: 30px;
font-size: 14px;
border-bottom: solid 1px #f1f1f1;
background: #ffffff;
}
li:last-child{
border-bottom: none;
}
li:hover{
background: #f6f6f6;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment