简易搜索组件(vue键盘事件)
<template>
<div class="hello">
<h1>值:{{text}}</h1>
<div
class="box"
@keydown.down="increment"
@keydown.up="decrement"
@keydown.enter="go"
>
<div class="search_box">
<div class="search_box_wrapper">
<input
id="search"
ref="search"
v-model="q"
class="search_input"
placeholder="搜索"
type="search"
autocomplete="off"
@focus="onFocus"
@blur="onBlur"
/>
</div>
<ul
v-show="focus && results.length"
class="search_list"
style="margin-top: 37px"
>
<li
v-for="(result, index) of results"
:key="result.title + index"
@mouseenter="focusIndex = index"
@mousedown="go"
>
<div
class="link"
:class="{
link_active: focusIndex === index,
}"
@click="focus = false"
>
<span v-if="result.title" style="font-weight: bold">{{
result.title
}}</span>
</div>
</li>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
q: "",
focus: false,
focusIndex: -1,
allResults: [
{ title: '1' },
{ title: '11' },
{ title: '2' },
{ title: '22' },
{ title: '3' },
{ title: '33' },
{ title: '4' },
{ title: '44' },
{ title: '5' },
{ title: '55' },
],
results: [],
text: ''
};
},
watch: {
q(q) {
this.focusIndex = -1
if (!q) {
this.results = []
return
}
this.results = []
for (let i = 0; i < this.allResults.length; i++) {
if(this.allResults[i].title.includes(q)) {
this.results.push(this.allResults[i])
}
}
}
},
methods: {
onFocus() {
this.focus = true;
this.$emit("focus", true);
},
onBlur() {
this.focus = false;
this.$emit("focus", false);
},
increment() {
if (this.focusIndex < this.results.length - 1) {
this.focusIndex++;
}
},
decrement() {
if (this.focusIndex >= 0) {
this.focusIndex--;
}
},
go() {
if (this.results.length === 0) {
return;
}
this.$refs.search.blur();
this.q = "";
this.text = this.results[this.focusIndex].title
},
},
};
</script>
<style scoped>
ul {
list-style: none;
margin: 0;
padding: 0;
margin-bottom: 1.25rem;
}
li {
position: relative;
padding-left: 1.75em;
margin: 0.5rem 0;
}
.hello {
width: 100%;
height: 100%;
}
.box {
display: block;
width: 100%;
position: relative;
display: flex;
flex-direction: column;
/* align-items: center; */
justify-content: space-between;
}
.search_box {
width: 100%;
}
.search_box_wrapper {
position: relative;
}
.search_input {
display: block;
width: 100%;
padding: 0.5rem 0.75rem 0.5rem 2.5rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1.25rem;
border: 1px solid transparent;
color: #374151;
border-radius: 0.375rem;
background: #e5e7eb;
}
.search_input::placeholder {
color: #6b7280;
}
.search_input:focus {
border-color: #d1d5db;
outline: none;
background: white;
}
.search_list {
position: absolute;
width: 100%;
flex: 1;
top: 0;
background: white;
border: 1px solid #d1d5db;
overflow: hidden;
z-index: 10;
border-radius: 0.375rem;
max-height: 500px;
overflow-y: auto;
}
.link_active {
color: #10b981;
background: #e5e7eb;
}
</style>
本文来自博客园,作者:暗鸦08,转载请注明原文链接:https://www.cnblogs.com/DarkCrow/p/16555244.html

浙公网安备 33010602011771号