Vue搜索栏过滤嵌套JSON数据 支持匹配深层字段问题咨询
修改后的完整代码
<script setup> import { computed, reactive, ref } from "vue"; const stores = reactive([]); const mySearch = ref(""); fetch("http://localhost:8081/sample.json") .then((res) => res.json()) .then((data) => { data.forEach(el => { stores.push(el) }); }) const filterStores = computed(() => { const keyword = mySearch.value.trim().toLowerCase() // 空搜索直接返回全量数据 if (!keyword) return stores return stores.map(store => { // 先过滤当前门店下符合条件的分区 const matchedSections = store.data.filter(section => { // 匹配分区名称 const sectionMatch = section.section_name.toLowerCase().includes(keyword) // 匹配分区下的商品 const itemMatch = section.items.some(item => item.toLowerCase().includes(keyword)) // 匹配到门店名称时保留该门店全部分区 const storeMatch = store.store.toLowerCase().includes(keyword) return storeMatch || sectionMatch || itemMatch }) // 仅保留存在匹配分区的门店 if (matchedSections.length > 0) { return {...store, data: matchedSections} } return null }).filter(Boolean) // 清理无匹配内容的空门店数据 }) </script> <template> <main> <div class="container-fluid"> <div class="row header"> <div class="d-flex justify-content-center mt-0 p-4"> <input type="text" placeholder="搜索门店、分区、商品" class="form-control form-control-lg" v-model="mySearch"/> </div> </div> <div class="row"> <div class="container"> <div v-for="(store, index) in filterStores" :key="`store-${index}`"> <li>{{ store.store }}</li> <!-- 可选:展示匹配的分区和商品 --> <ul> <li v-for="(section, secIdx) in store.data" :key="`sec-${secIdx}`"> 分区:{{section.section_name}} <ul> <li v-for="(item, itemIdx) in section.items" :key="`item-${itemIdx}`"> {{item}} </li> </ul> </li> </ul> </div> </div> </div> </div> </main> </template>
可选简化方案(仅过滤门店,不隐藏无关分区)
如果不需要隐藏门店下的无关分区,仅需要过滤有匹配内容的门店,可以把filterStores的逻辑简化为:
const filterStores = computed(() => { const keyword = mySearch.value.trim().toLowerCase() if (!keyword) return stores return stores.filter(store => { // 匹配门店名 if (store.store.toLowerCase().includes(keyword)) return true // 匹配任意分区名 if (store.data.some(section => section.section_name.toLowerCase().includes(keyword))) return true // 匹配任意商品 if (store.data.some(section => section.items.some(item => item.toLowerCase().includes(keyword)))) return true return false }) })
内容的提问来源于stack exchange,提问作者pandaseatpotatos
相关产品推荐
相关产品推荐

