Vue.js 3如何基于现有房屋列表代码实现文本输入搜索过滤功能
实现步骤
你只需要修改3处代码即可完成过滤功能:
- 在
data中新增search响应式变量,绑定你已经写好的输入框 - 新增
computed计算属性filteredHouses,实现城市、街道的匹配逻辑 - 修改模板中
v-for的遍历源为过滤后的数组
完整修改后代码
<template> <div class="search__sort"> <input v-model="search" placeholder="Search for a house"> <button class="sort__button">Price</button> <button class="sort__button">Size</button> </div> <!-- 这里把原来的houses替换为filteredHouses --> <div v-for="house in filteredHouses" :key="house.id" class="house"> <router-link :to="{ name: 'HouseDetails', params: { id: house.id}}" > <h2>ID = {{ house.id }}</h2> <h3> {{ house.location.street}} </h3> <img :src="house.image" /> </router-link> <button v-if="house.madeByMe" class="delete" @click="deleteHouse(house.id)">Delete</button> </div> </template> <script> import axios from 'axios' export default { name: 'Houses', data(){ return { houses: [], search: '' // 新增搜索关键词变量 } }, // 新增计算属性实现过滤 computed: { filteredHouses() { const keyword = this.search.trim().toLowerCase() // 搜索框为空时返回全部房屋 if (!keyword) return this.houses return this.houses.filter(house => { // 匹配街道,大小写不敏感 const matchStreet = house.location?.street?.toLowerCase().includes(keyword) // 匹配城市,如果你房屋数据的城市字段名不是city,自行替换为实际字段 const matchCity = house.location?.city?.toLowerCase().includes(keyword) return matchStreet || matchCity }) } }, created() { this.getHouses(); }, methods: { getHouses(){ // GET request using axios with set headers const headers = { "CENSORED": "CENSORED" }; axios.get('myAPI', { headers }) .then(response => this.houses = response.data); }, deleteHouse(id) { const headers = { "CENSORED": "CENSORED" }; axios.delete('myAPI' + id, { headers }) .then(response => { console.log(response); // 可选优化:删除成功后直接更新本地列表,不用重新调用接口 this.houses = this.houses.filter(item => item.id !== id) }) .catch(function (error) { console.log(error.response); }); }, }, } </script>
补充说明
如果需要扩展支持更多字段的匹配(比如房屋名称、区域等),直接在filter的判断逻辑中新增对应字段的匹配规则即可。
内容的提问来源于stack exchange,提问作者Michał Różga
相关产品推荐
相关产品推荐

