背景需求:公司要求一个下拉框能够支持搜索,手动输入,下拉框没有自己需要的值时,支持手动输入,并自动保存进数据库
公司使用的UI框架是Ant Design of Vue,找到了Select选择器组件,但是这个组件功能有点复杂了,不太适合公司需要,所以我打算自己制作一个自定的组件来实现功能
效果图
代码部分
html部分
<body>
<div id="app">
<drop-down :arr="arr"></drop-down>
<drop-down :arr="arr"></drop-down>
<drop-down :arr="arr"></drop-down>
</div>
</body>
<script>
new Vue({
el: "#app",
data: {
arr: ["ddd", "aa", "ccc", "eeeee", "dssss"],
d:"dddd",
},
methods:{
}
});
</script>
js部分
Vue.component("drop-down", {
props: ["arr", "value"],
data() {
return {
isshow: false,
input_val: "",
li_arr: [],
}
},
template: `<div id="dropdown">
<div class="inp" @click.stop="show">
<input type="text" placeholder="请选择" @input="handleInput" v-model="input_val">
</div>
<div class="select" v-if="isshow">
<ul class="select_ul">
<li v-for="(item,index) in li_arr" :key="index" @click="select(item)">{{item}}</li>
</ul>
</div>
</div>`,
methods: {
show() {
this.isshow = true;
this.li_arr = this.arr;
},
select(val) {
this.input_val = val;
this.isshow = false;
},
handleInput() {
var patt = new RegExp(this.input_val);
this.li_arr = [];
this.arr.forEach(item => {
if (patt.test(item)) {
this.li_arr.push(item)
}
});
}
},
mounted() {
document.addEventListener('click', () => {
this.isshow = false;
})
}
});
css部分
* {
margin: 0;
padding: 0;
}
#dropdown {
width: 10%;
position: relative;
background-color: aqua;
box-sizing: border-box;
}
.inp input {
width: 100%;
min-height: 32px;
border: 1px solid #d9d9d9;
outline: none;
}
.select {
width: 100%;
max-height: 220px;
position: absolute;
top: 34px;
left: 0;
/* display: none; */
overflow-y: auto;
transition: all 3s;
box-shadow: 0px 0px 20px #d9d9d9;
background-color: white
}
.select .select_ul li {
padding: 8px;
cursor: pointer;
color: #595959;
}
.select .select_ul li:hover {
background-color: #e6f7ff;
}
.selectactive {
background-color: #e6f7ff;
}
缺点
暂时无法实现v-model,传值需要在父组件里传递,子组件处理后再传回来
总结
这个组件基本实现了搜索和文本输入的功能,比起Ant Design of Vue 组件,简洁了很多,虽然无法实现v-model,哈哈,这个我再研究研究(我这个小白还需要成长,哈哈)。