Vue实现typeahead组件功能(非常靠谱)

2020-06-13 10:45:24易采站长站整理

<p class="noFound" v-show="typeaheadData && typeaheadData.length === 0">未能查询到,请重新输入!</p>
</div>
</transition>
</div>
</div>
</template>
<script>
export default {
name: 'selectSearch',
data: function () {
return {
placeholderValue: '',// 给看到选择内容的
isExpand: false,
searchVal: '', // 搜索关键字
resultVal: '', // 保存搜索到的值
searchList: [], //保存过滤的结果集
currentIndex: -1, // 当前默认选中的index,
}
},
computed: {
mapFormatData () { // 外部有传入格式的时候映射mapData
return this.mapData.map(item => {
item[this.mapDataFormat.value] = item[this.mapDataFormat.value];
return item;
});
},
typeaheadData () {
let temp = [];
if (this.searchVal && this.searchVal === '') {
return this.mapFormatData;
} else {
this.currentIndex = -1; // 重置特殊情况下的索引
this.mapFormatData.map(item => {
if (item[this.mapDataFormat.label].indexOf(this.searchVal.toLowerCase().trim()) !== -1) {
temp.push(item)
}
return item;
})
return temp;
}
}
},
props: {
placeholder: {
type: String,
default: '--请选择--'
},
emptyText: {
type: String,
default: '暂无数据'
},
mapData: { // 外部传入的列表数据
type: Array,
default: function () {
return [] }
},
mapDataFormat: { // 映射传入数据的格式
type: Object,
default: function () {
return {
label: 'text',
value: 'value',
extraText: 'extraText'
}
}
},
asyncData: { // 实时响应的值
type: [Object, String],
default: function () {
return {}
}
}
},
methods: {
showHideMenu (e) { // 点击其他区域关闭下拉列表
if (e) {
if (this.$refs.selectSearch && this.$refs.selectSearch.contains(e.target)) {
this.isExpand = true;
} else {
this.isExpand = false;
}
}
},
resetDefaultStatus () { // 清除所有选中状态
this.searchVal = '';
this.currentIndex = -1;
this.typeaheadData.map(item => {
this.$delete(item, 'active');
})
},
setActiveClass (index) { // 设置样式活动类
this.typeaheadData.map((item, innerIndex) => {
if (index === innerIndex) {
this.$set(item, 'active', true);
this.currentIndex = index; // 这句话是用来修正index,就是键盘上下键的索引,不然会跳位
} else {