效果图如下:
当 鼠标 点击 输入框时,显示下拉滚动列表,点击后采用赋值给 输入框; 在输入框中输入值可以再我们的下拉列表数据中进行模糊匹配
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手写一个select</title>
<div id ="app">
<input type="text" class="my_input" v-model.trim="inputValue" @click="openSelect">
<div class="my_select" v-show="showMySelect">
<ul>
<li v-for="(item, index) in datas" :key= index>
<div class="select_item" @click="getClickItem(index)" v-show="canShowItem(item.value)">
{{item.value}}
</div>
</li>
</ul>
</div>
</div>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
datas: [{
value: '蒜薹炒肉'
},{
value: '莴笋炒肉'
},{
value: '笋子炒肉'
},{
value: '红烧牛腩'
},{
value: '干锅兔'
},{
value: '番茄炒鸡蛋'
},{
value: '红烧牛腩'
},{
value: '干煸鸡'
},{
value: '红油抄手'
},{
value: '蒸饺'
}],
inputValue: null,
showMySelect: false
},
methods: {
getClickItem(index) {
this.inputValue = this.datas[index].value;
this.showMySelect = false;
},
openSelect() {
this.showMySelect = true;
},
submit() {
console.log(this.inputValue)
}
},
computed: {
canShowItem() {
return (value) => {
if (this.inputValue != null && this.inputValue.length > 0 ) {
return value.indexOf(this.inputValue) >= 0;
} else {
return true;
}
}
}
}
})
</script>
<style scoped >
ul {
list-style: none;
padding-inline-start: 0;
max-height: 200px;
overflow-y: scroll;
}
.my_input {
width: 100%;
}
.my_select {
background-color: rgb(211, 211, 211);
width: inherit;
text-align: center;
}
.select_item {
height: 32px;
}
#app {
width: 400px;
height: 400px;
}
</style>
</body>
</html>