Ionic 3搜索栏功能异常:过滤数据无法显示且删除文本报错
解决Ionic 3搜索栏过滤显示与清空卡顿问题
看起来你遇到的问题主要来自两个关键的代码逻辑问题,咱们一步步来修复:
问题1:过滤结果结构错误,导致页面无法渲染
你在过滤后执行了filterFood.push( {food} ),这会把过滤得到的食物数组包裹成一个对象(结构变成[{food: [食物1, 食物2]}]),而模板里是直接遍历food数组并访问item.name,这时候每个item其实是那个包含food属性的对象,自然取不到对应的属性值。
问题2:原始数据被覆盖,空搜索时错误处理缺失
- 你直接把
this.food替换成了过滤后的结果,这样清空搜索文本时,没有原始数据可以恢复,无法回到初始状态。 - 当
queryText为空时,调用this.queryText.toString()会抛出错误(空值没有toString方法),这就是删除文本时卡顿的原因。
修正后的完整代码
TypeScript部分
首先保存一份原始数据的副本,用来在清空搜索时恢复数据;同时修正过滤逻辑,去掉多余的对象包裹:
public food: any[]; public originalFood: any[]; // 保存原始数据副本 queryText: string = ''; // 初始化空字符串,避免空值问题 // 在获取数据的钩子(比如ngOnInit)里初始化原始数据 ngOnInit() { // 替换成你实际获取原始食物数据的逻辑 this.originalFood = [/* 你的完整食物数据 */]; this.food = [...this.originalFood]; // 初始显示全部数据 } updateText() { // 处理空搜索:直接恢复原始数据 if (!this.queryText) { this.food = [...this.originalFood]; return; } const queryTextLower = this.queryText.toLowerCase(); // 直接基于原始数据过滤,无需额外数组包裹 const filteredFood = _.filter(this.originalFood, t => t.name.toLowerCase().includes(queryTextLower) ); this.food = filteredFood; console.log(filteredFood); }
HTML部分
模板无需大改,确保遍历的是正确的数组即可:
<ion-toolbar> <ion-searchbar aria-placeholder="search" [(ngModel)]="queryText" (ionInput)="updateText()" ></ion-searchbar> </ion-toolbar> <ion-item> <ion-label>Name</ion-label> <ion-label>Description</ion-label> <ion-label>Price</ion-label> </ion-item> <ion-item *ngFor="let item of food"> <ion-label style="width: 40px; height: 80px;">{{item.name}}</ion-label> <ion-label style="width: 40px; height: 80px;">{{item.description}}</ion-label> <ion-label style="width: 40px; height: 80px;">{{item.price}}</ion-label> </ion-item>
关键修改点说明
- 保存原始数据:用
originalFood存储初始完整数据,确保搜索、清空操作都基于原始数据源,不会丢失数据。 - 空值处理:当搜索文本为空时,直接重置
food为原始数据副本,避免空值调用toString的错误,同时恢复全部数据显示。 - 修正过滤结构:直接使用
_.filter返回的数组赋值给this.food,去掉多余的对象包裹,让模板能正常遍历单个食物对象,访问name等属性。
这样修改后,过滤后的内容应该能正常显示,清空搜索文本时也不会出现错误和卡顿了。
内容的提问来源于stack exchange,提问作者JohnnyCc
相关产品推荐
相关产品推荐

