废话不多说先看效果:

代码如下:
<template>
<div style="padding-left: 3px; margin-top: 3px">
<!-- 搜索框 -->
<div class="input-warp">
<input
class="input"
v-model="keyWord"
type="text"
placeholder="输入城市名称进行查找"
/>
<el-button class="input-search" icon="el-icon-search" circle></el-button>
</div>
<div class="searchList" v-if="keyWord">
<ul>
<li
v-for="(item, index) in searchData"
:key="index"
@click="chooseCode(item)"
>
{{ item.name }}
</li>
<li v-if="searchData.length == 0">暂无相关城市,请换个城市进行搜索</li>
</ul>
</div>
</div>
</template>
<script>
import { searchCityList } from "@/api/homeApi";
export default {
data() {
return {
keyWord: "",
searchData: [],
};
},
created() {},
watch: {
//这里监听监听输入框的值,如果发生改变执行接口方法
keyWord: {
handler(newv, oldv) {
this.getSearchData();
},
},
},
mounted() {},
methods: {
//获取用户输入城市的列表
getSearchData() {
searchCityList({ cityName: this.keyWord }).then((res) => {
if (res.success == true) {
console.log(res.data);
this.searchData = res.data.list;
}
});
},
//当用户点击搜索出来的城市之后
chooseCode(data) {
// console.log(data);
this.$store.commit("CHANGE_CITYCODE", data.code);
this.$store.commit("CHANGE_CITYNAME", data);
this.$store.commit("CHANGE_CITYDIALOG", false);
if (window.location.pathname == "/houseDetail") {
this.$router.push({ path: "/house" });
}
this.$router.go(0);
},
},
};
</script>
<style scoped lang="less">
// 搜索框
.input-warp {
position: relative;
.input {
border: none;
width: 766px;
height: 50px;
box-sizing: border-box;
opacity: 0.9;
background: #ffffff;
border: 1px solid #fff;
padding: 0 55px 0 25px;
border-radius: 25px;
box-shadow: 0px 1px 4px 0px rgba(146, 146, 146, 0.6);
&:focus-visible {
outline: none;
}
}
::v-deep .input-search {
position: absolute;
top: 7px;
right: 422px;
color: #fff;
text-align: center;
width: 36px;
height: 36px;
opacity: 1;
background: linear-gradient(90deg, #3493ff, #485cff);
border-radius: 50%;
box-shadow: 0px 1px 4px 0px rgba(146, 146, 146, 0.6);
.el-icon-search {
font-size: 19px;
margin: -4px;
}
}
}
.searchList {
width: 766px;
// height: 300px;
box-shadow: 0px 1px 4px 0px rgb(146 146 146);
padding: 15px 0;
// padding-left: 26px;
box-sizing: border-box;
overflow: auto;
}
li {
list-style: none;
line-height: 40px;
font-size: 16px;
padding-left: 26px;
}
li:hover {
cursor: pointer;
background: #f8f8f9;
}
</style>

本文介绍如何在 Vue 中创建一个输入框,实现实时搜索功能。通过示例代码展示具体的实现过程。
1万+

被折叠的 条评论
为什么被折叠?



