class dataType { price: number = 0 name: string = '' } @Entry @Component struct ColorGradientExample { @State sortOrder: 'asc' | 'desc' | 'default' = 'default'; @State data: dataType[] = [ { price: 112, name: "A商品" }, { price: 134, name: "B商品" }, { price: 12, name: "C商品" }, { price: 54, name: "D商品" }, { price: 43, name: "E商品" }, { price: 25, name: "F商品" }, { price: 65, name: "G商品" }, { price: 34, name: "H商品" }, { price: 5, name: "I商品" }, { price: 90, name: "J商品" }, ] @State dataCopy: dataType[] = [] aboutToAppear(): void { this.dataCopy = [...this.data] } build() { Column() { ForEach(this.data, (item: dataType) => { Row() { Text(item.name) Text(item.price + '') } }) // 按钮用于切换排序状态 Button('切换排序') .onClick(() => { this.handleSortClick(); }) .margin({ top: 20 }) } } // 假设的排序函数 sortData(order: 'asc' | 'desc' | 'default'): void { if (order === 'asc') { this.data.sort((a, b) => a.price - b.price); } else if (order === 'desc') { this.data.sort((a, b) => b.price - a.price); } else { this.data = [...this.dataCopy] } } // 按钮点击事件处理函数 private handleSortClick(): void { switch (this.sortOrder) { case 'asc': this.sortOrder = 'desc'; this.sortData('desc'); break; case 'desc': this.sortOrder = 'default'; this.sortData('default'); // 如果默认不需要排序,这里可以不做处理或重置列表顺序 break; case 'default': this.sortOrder = 'asc'; this.sortData('asc'); break; } } }
鸿蒙升序降序恢复默认
于 2024-07-22 16:59:47 首次发布