要在uniapp中实现根据输入的res
搜索并匹配company.name
以展示结果,你可以采用如下步骤:
- 为你的搜索框添加一个
v-model
来双向绑定输入的值。 - 创建一个计算属性,该属性根据绑定的搜索框值来过滤数组。
- 在
v-for
循环中使用过滤后的数组而不是原始数组。
下面是如何实现这个功能的具体代码:
首先,确保你的data里有一个属性来存储用户输入的搜索内容:
解释
export default { data() { return { siteList: [], // 你的原始公司列表 searchInput: '' // 绑定搜索框的内容 }; }, computed: { // 计算属性来处理过滤逻辑 filteredList() { // 如果搜索框为空,返回原始数组 if (!this.searchInput) { return this.siteList; } // 使用filter方法根据输入的内容过滤数组 return this.siteList.filter(company => { return company.name.toLowerCase().includes(this.searchInput.toLowerCase()); }); } }, methods: { companyInput(res) { this.searchInput = res; // 更新搜索框的内容 } } };
Copy
然后,在你的模板中,使用计算属性filteredList
来代替siteList
:
解释
<template> <!-- 搜索框 --> <input type="text" v-model="searchInput" placeholder="搜索公司名称" @input="companyInput"> <!-- 公司列表 --> <view v-for="(company, index) in filteredList" :key="index"> <uni-card :title="company.name" :extra="company.createUserName"> <!-- 卡片内容 --> <view class="uni-body">地址: {{ company.provinceName }}/{{ company.cityName }}/{{ company.districtName }}{{ company.powerSupplyName === undefined ? '' : ' / ' + company.powerSupplyName }}</view> <!-- 其他内容 --> <!-- ... --> </uni-card> </view> </template>
Copy
这样,当用户在搜索框中输入内容时,filteredList
计算属性会实时更新,并只显示匹配搜索条件的公司列表。如果搜索框为空,计算属性会返回原始的siteList
数组,从而显示所有公司信息。
注意,这里假设了siteList
是已经定义好的,并且拥有name
属性。另外,搜索功能是大小写不敏感的,因为使用了toLowerCase()
方法。如果你希望搜索是大小写敏感的,你可以去掉这两个方法。