vue实现对数据进行升序降序排列

单个属性排序:

在这里插入图片描述


<template><div><button type="button" @click="sx()">{{sxpl}}</button><button type="button" @click="jx()">{{jxpl}}</button><ul><li v-for="item in sortedList" :key="item.name">{{ item.name }} - {{ item.price }}</li></ul></div>
</template><script>
export default {data() {return {list: [{ name: '物品1', price: 20 },{ name: '物品2', price: 50 },{ name: '物品3', price: 10 },{ name: '物品4', price: 30 }],ascending: false ,// 标记当前是否为升序排序sxpl:'价格从低到高',jxpl:'价格从高到低',descending: false// 标记当前是否为降序排序};},computed: {sortedList() {const newList = this.list.slice(); // 克隆一份原始数组if(this.ascending == false && this.descending == false){return this.list}if(this.ascending == true){newList.sort((a, b) =>  (a.price - b.price)); // 使用比较器进行排序return newList;  }if(this.descending == true){newList.sort((a, b) =>  (b.price - a.price)); // 使用比较器进行排序return newList; }}},methods: {sx(){this.ascending = !this.ascendingthis.descending = false},jx(){this.descending = !this.descendingthis.ascending = false}}
};
</script>


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部