1、方法 (js)sort()数组排序
sort()默认按照字符串排序,reverse()可以倒序
const arr = ['d', 's', 'a', 'c', 'b']
console.log(arr.sort())//[ 'a', 'b', 'c', 'd', 's' ]
const arr2 = [7, 6, 9, 18, 12]
console.log(arr2.sort())//[ 12, 18, 6, 7, 9 ]
//这里之所以不是[6,7,9,12,18]是因为sort()默认按照字符串排序,他会默认把12,18先取1往后比较
const arr3 = arr2.sort((a, b) => {
return a - b
})
console.log(arr3)//[ 6, 7, 9, 12, 18 ]
//从小到大排序,
2、简单升降序
html:
//v-if 就是当变量flag为true时创建改按钮为非true时删除
//然后绑定点击事件
<button v-if="flag" @click="sortFun">升序</button>
<button v-if="!flag" @click="sortFun">降序</button>
data:
// flag: true, //定义显示隐藏的变量
script:
//排序方法 —— 通过id 要是通过价格的话直接用price替换掉id就可以了
sortFun() {
if (this.flag) {
this.lcList.sort((a, b) => {
return a.id - b.id;
});
} else {
this.lcList.sort((a, b) => {
return b.id - a.id;
});
}
this.flag = !this.flag;
},