前端vue3实现类似于百度的搜索框
时间: 2023-05-27 08:06:34 浏览: 309
以下是基于Vue3实现类似于百度的搜索框的示例代码:
HTML模板:
```
<template>
<div class="search-box">
<div class="search-input">
<input type="text" v-model="keyword" @input="search" />
<button @click="submit">搜索</button>
</div>
<ul class="search-list" v-show="showList">
<li v-for="(item, index) in searchList" :key="index" @click="selectItem(item)">{{ item }}</li>
</ul>
</div>
</template>
```
CSS样式:
```
.search-box {
position: relative;
width: 400px;
height: 40px;
margin: 0 auto;
}
.search-input {
position: relative;
width: 100%;
height: 100%;
}
.search-input input {
width: 100%;
height: 100%;
border: none;
outline: none;
box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);
border-radius: 20px;
padding: 0 20px;
font-size: 16px;
}
.search-input button {
position: absolute;
top: 0;
right: 0;
width: 80px;
height: 100%;
background-color: #3385ff;
border: none;
outline: none;
color: #fff;
font-size: 16px;
border-top-right-radius: 20px;
border-bottom-right-radius: 20px;
cursor: pointer;
}
.search-list {
position: absolute;
top: 40px;
left: 0;
width: 100%;
max-height: 200px;
overflow-y: auto;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 3px;
box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
z-index: 99;
}
.search-list li {
padding: 10px;
cursor: pointer;
}
.search-list li:hover {
background-color: #f2f2f2;
}
```
JavaScript代码:
```
<script>
import { reactive } from 'vue';
export default {
setup() {
const state = reactive({
keyword: '',
searchList: [],
showList: false,
});
// 模拟搜索函数
const searchFn = () => {
const list = [];
for (let i = 0; i < 10; i++) {
list.push(state.keyword + i);
}
state.searchList = list;
state.showList = true;
};
// 监听输入框的变化,并触发搜索函数
const search = () => {
if (state.keyword.trim() === '') {
state.showList = false;
state.searchList = [];
return;
}
searchFn();
};
// 提交搜索
const submit = () => {
if (state.keyword.trim() === '') {
return;
}
// TODO: 处理搜索结果
};
// 点击搜索列表项
const selectItem = (item) => {
state.keyword = item;
state.showList = false;
};
return {
keyword: state.keyword,
searchList: state.searchList,
showList: state.showList,
search,
submit,
selectItem,
};
},
};
</script>
```
以上代码实现了一个简单的搜索框,包括输入框、搜索按钮和搜索结果列表。当输入框内容发生变化时,会触发搜索函数,搜索结果会显示在下拉列表中。用户可以通过点击下拉列表中的项来选择搜索关键字,也可以直接点击搜索按钮提交搜索请求。
阅读全文