點擊按鈕第一次實現升序,再次點擊的時候實現降序,
(這里只提供了JS代碼及思路)
這里實現的是價格的排序
首先定義一個數組:
mallList: [ { id: 1, img: 'https://tse2-mm.cn.bing.net/th/id/OIP.B5xAajd2dWNwJn2Q7IY-IQHaEK', title: '霍尼韋爾H910Plus系列KN95防霧系列KN95防霧系列KN95防霧霾口罩', money: 105, num: 550 }, { id: 2, img: 'https://tse2-mm.cn.bing.net/th/id/OIP.B5xAajd2dWNwJn2Q7IY-IQHaEK', title: '家用洗臉毛巾', money: 110, num: 1000 }, { id: 3, img: 'https://tse2-mm.cn.bing.net/th/id/OIP.B5xAajd2dWNwJn2Q7IY-IQHaEK', title: '小霸王牌多功能電飯鍋', money: 15, num: 700 }, { id: 4, img: 'https://tse2-mm.cn.bing.net/th/id/OIP.B5xAajd2dWNwJn2Q7IY-IQHaEK', title: '自助飲食', money: 99, num: 680 } ],
創建升序降序的方法,並且帶入
priceSort(e) { // console.log("價格排序"); let num = this.data.number ++; if( num % 2 == 0 ){ this.ascending() //升序 } else { this.descending() //降序 } }, // 升序 ascending(){ let mallList = this.data.mallList; //獲取數組 mallList.sort(function (a, b) { return a.money - b.money; }) this.setData({ mallList: mallList }) }, // 降序 descending(){ let mallList = this.data.mallList; //獲取數組 mallList.sort(function (a, b) { return b.money - a.money; }) this.setData({ mallList: mallList }) },
還有第二種方法:
在data中定義實例 data: { a: 1, }, btn(){ if (this.a==1){ this.a=2 }else{ this.a=1 } }
基本思路就是這樣了。
文章部分參考:https://blog.csdn.net/m0_52438421/article/details/109682586