用elementui写一个搜索框,功能类似百度搜索框,我的api:'http://192.168.2.106:9000/ceshi'
时间: 2024-11-30 08:28:47 浏览: 45
在Element UI中创建一个类似百度搜索框的功能,你可以结合`el-input`、`el-autocomplete`组件以及`axios`来进行网络请求。下面是一个基本的步骤:
1. 首先,在HTML中引入必要的Element UI库和`axios`库,如果还没有导入,可以在`<head>`部分添加:
```html
<script src="https://cdn.jsdelivr.net/npm/element-ui/lib/index.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
```
2. 创建一个Vue实例,并在其中设置搜索框组件和相关方法:
```html
<template>
<div>
<el-input
v-model="searchQuery"
placeholder="请输入搜索关键词..."
:remote-method="search"
:fetch-first="true"
@search="handleSearch"
></el-input>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
searchQuery: '',
};
},
methods: {
search(query) {
return axios.get(`http://192.168.2.106:9000/ceshi?query=${encodeURIComponent(query)}`);
},
handleSearch(searchData) {
// 这里假设`searchData`是来自后端的搜索结果,处理并展示它
// 例如,你可以遍历数据并使用`el-option`生成选项
Object.keys(searchData).forEach(item => {
this.options.push({ value: item, label: searchData[item] });
});
},
},
computed: {
options() {
return this.searchQuery ? [] : this.previousOptions || [];
},
previousOptions() {
return this.$store.state.searchOptions || []; // 如果需要从Vuex store获取之前保存的结果
},
},
};
</script>
```
3. 在上述代码中,`remote-method`属性告诉`el-autocomplete`组件当你输入时应该去远程查询。`fetch-first`属性让组件立即获取第一条匹配结果。`@search`事件在输入发生变化时触发,传递给`handleSearch`函数。
4. 当用户开始搜索时,`search`方法会被调用,并将`searchQuery`编码后作为URL参数发送到指定的API。`handleSearch`方法接收到返回的数据,并将其转换成`el-option`的选项结构。
5. 对于持久化搜索历史,你可以考虑使用Vuex或者其他状态管理工具将搜索结果缓存起来,以便在用户关闭窗口后再次打开页面时仍能显示之前的搜索结果。
注意:这个示例假设你的后端API返回的是一个JSON对象,每个键值对对应一项搜索结果。请根据实际情况调整API的响应格式和处理方式。
阅读全文
相关推荐










