点击同一个按钮,实现数组的升序降序切换


点击按钮第一次实现升序,再次点击的时候实现降序,

(这里只提供了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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM