img

概述

本教程将介绍如何在HarmonyOS应用中实现一个功能完整的景点列表页面。我们将学习如何实现搜索功能、数据过滤、列表展示等核心功能。

核心功能

  • 搜索功能实现
  • 数据过滤和查询
  • 列表页面布局
  • 加载状态管理

代码实现

1. 页面状态定义

@Entry
@Component
struct ScenicSpotsList {
  @State type: number = 0;
  @State source: string = ''  // 数据来源 city ==> 城市列表
  @State sourceId: number = 0 // 数据来源的id 用于查找筛选
  @State @Watch('handleSearch') inputText: string = '' // 搜索文本
  @State title: string = '热门景点'
  @State hotCartList: strategyParent[] = []
  @State loadingStatus: string = ''
}

2. 搜索功能实现

handleSearch(propName: string): void {
  this.getHotScenicHandle()
}

// 获取热门景点数据
getHotScenicHandle() {
  this.loadingStatus = LoadingStatus.LOADING
  this.loadObjectInfo().then(async (res: ObjectTypeInfo) => {
    if (this.inputText.trim() && this.sourceId == 0) {
      // 仅搜索文本
      this.hotCartList = await cloud.database({ objectTypeInfo: res })
        .collection(strategyParent)
        .query()
        .contains('title', this.inputText)
        .get();
    } else if (!this.inputText.trim() && this.sourceId !== 0) {
      // 仅按城市筛选
      this.hotCartList = await cloud.database({ objectTypeInfo: res })
        .collection(strategyParent)
        .query()
        .equalTo('cityId', this.sourceId)
        .get();
    } else if (this.inputText.trim() && this.sourceId !== 0) {
      // 组合查询
      this.hotCartList = await cloud.database({ objectTypeInfo: res })
        .collection(strategyParent)
        .query()
        .equalTo('cityId', this.sourceId)
        .contains('title', this.inputText)
        .get();
    } else {
      // 获取全部数据
      this.hotCartList = await cloud.database({ objectTypeInfo: res })
        .collection(strategyParent)
        .query()
        .get();
    }
    this.loadingStatus = LoadingStatus.SUCCESS
  }).catch(() => {
    this.loadingStatus = LoadingStatus.FAILED
  })
}

3. 页面布局实现

build() {
  Column() {
    CommonNavbar({ title: this.title, inputText: this.inputText })
    if (this.loadingStatus === LoadingStatus.LOADING) {
      MyLoadingProgress()
    } else if (this.loadingStatus === LoadingStatus.FAILED) {
      notFound()
    } else {
      List({ space: StyleConstants.SPACE_TWENTY }) {
        ListItem() {
          Column() {
            CardComponents({ hotCartList: this.hotCartList })
          }
        }
      }
    }
  }
  .width('100%')
  .height('100%')
  .backgroundColor($r('app.color.page_background'))
}

关键技术点

1. 数据查询优化

根据不同的查询条件组合,实现灵活的数据过滤:

  • 纯文本搜索
  • 城市筛选
  • 组合查询
  • 全量数据获取

2. 状态监听

使用@Watch装饰器监听搜索输入变化:

@Watch('handleSearch') inputText: string = ''

总结

通过本教程,我们学习了如何实现一个功能完整的景点列表页面。重点掌握了HarmonyOS中的数据查询、状态管理、列表展示等关键技术。这些知识将帮助开发者构建更好的HarmonyOS应用。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐