Vue折腾记 - (3)写一个不大靠谱的typeahead组件

2023-06-07,,

Vue折腾记 - (3)写一个不大靠谱的typeahead组件
2017年07月20日 15:17:05
阅读数:691
前言
typeahead在网站中的应用很多..今天跟着我来写一个不大靠谱的typeahead;

你能学到什么?

自定义事件
遍历的思想
功能细节的考虑
一切都挺不靠谱的…可完善的地方很多.废话不多说,看效果图

更新
2017-07-21: 完善逻辑及美化样式,所以效果图和代码都有所变动
效果图
这里写图片描述

有哪些功能点?

粗糙的模糊搜索 - 借助indexOf
ESC和blur事件清除输入框,没有找到匹配的情况下
Enter默认在找到只剩下一个情况下选中
方向盘的上下(已经阻止光标的移动)选中子项,回车选中
鼠标点击选择子项
搜索框清空情况下默认不触发自定义事件值的返回
鼠标移动+键盘方向键移动位置的同步
placeholder及遍历数据data支持外部传入,也就是绑定props;前者字符串,后者数组对象
代码
typeahead.vue

<input type="text" v-model="searchVal" @input="filterList(searchVal)" ref="input" :placeholder="placeholder" @keydown.down.prevent="selectChildWidthArrowDown" @keydown.up.prevent="selectChildWidthArrowUp" @keydown.enter="selectChildWidthEnter" @blur="ifNotFoundClear" @keydown.esc="ifNotFoundClear" autocomplete="off">

0 && isExpand ">
<li v-for="(item,index) in searchList" :key="index" :class="item.active ? 'active':''" @click="selectChild(index)" @mouseenter="setActiveClass(index)" @mouseleave="setActiveClass(index)">
{{item.text}}

未能查询到,请重新输入!

.el-fade-in-linear-enter-active,
.el-fade-in-linear-leave-active,
.fade-in-linear-enter-active,
.fade-in-linear-leave-active {
transition: opacity .2s linear;
}

.el-fade-in-enter,
.el-fade-in-leave-active,
.el-fade-in-linear-enter,
.el-fade-in-linear-leave,
.el-fade-in-linear-leave-active,
.fade-in-linear-enter,
.fade-in-linear-leave,
.fade-in-linear-leave-active {
opacity: 0;
}

.typeahead {
position: relative;
background-color: #fff;
a {
color: #333;
text-decoration: none;
padding: 5px;
}
ul {
list-style: none;
padding: 6px 0;
margin: 0;
overflow: visible;
li {
display: block;
width: 100%;
padding: 5px;
font-size: 14px;
padding: 8px 10px;
position: relative;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: #48576a;
height: 36px;
line-height: 1.5;
box-sizing: border-box;
cursor: pointer;
&.active {
background-color: #20a0ff;
a {
color: #fff;
}
}
}
}
input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #fff;
background-image: none;
border-radius: 4px;
border: 1px solid #bfcbd9;
box-sizing: border-box;
color: #1f2d3d;
font-size: inherit;
height: 36px;
line-height: 1;
outline: 0;
padding: 3px 10px;
transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
width: 100%;
display: inline-block;
}
.typeahead-header,
.typeahead-content {
width: 100%;
}
.typeahead-content {
position: absolute;
border-radius: 2px;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
box-sizing: border-box;
margin: 5px 0;
}

.noFound {
text-align: center;
}
}

总结
自此,一个挺粗糙的模糊搜索组件就完成了;

希望此文对于正在阅读的您有所收获~~

有更好的方案或者实现方法的可以留言…谢谢

Vue折腾记 - (3)写一个不大靠谱的typeahead组件的相关教程结束。

《Vue折腾记 - (3)写一个不大靠谱的typeahead组件.doc》

下载本文的Word格式文档,以方便收藏与打印。