假定数组menu如下:
menu: [{
zt: '已交',
obj: '语文',
dt: '2017-04-15',
},
{
zt: '未交',
obj: '数学',
dt: '2022-12-14',
},
{
zt: '已交',
obj: '英语',
dt: '2019-04-15',
}
]
初始页面渲染如下:
要求把数组menu中最新的日期排在最前面
代码如下:
<template> <div> <div class="wrapper"> <div class="main" v-for="(item,index) in menu" :key='index'> <div class="obj">{{item.obj}} {{item.dt}}</div> <div class="zt">{{item.zt}}</div> </div> </div> <button @click="test()">(点击排序)</button> </div> </template>
<script> export default { data() { return { menu: [{ zt: '已交', obj: '语文', dt: '2017-04-15', }, { zt: '未交', obj: '数学', dt: '2022-12-14', }, { zt: '已交', obj: '英语', dt: '2019-04-15', } ], } }, methods: { test() { var new_arr = []; var original_menu = this.menu; console.log(original_menu); // 去掉 - 号, 转换为数字类型 original_menu.forEach(function(item) { console.log("item.dt",item.dt); let temp_item; temp_item = item.dt; temp_item = +(temp_item.split('-').join('')); console.log("temp_item:", temp_item); new_arr.push({ zt: item.zt, obj: item.obj, dt: temp_item, }) }); console.log("新数组new_arr:", new_arr); // 选择排序 for (let i = 0; i < new_arr.length - 1; i++) { for (let j = i + 1; j < new_arr.length; j++) { if (new_arr[j].dt > new_arr[i].dt) { let min_dt, min_zt, min_obj; min_dt = new_arr[i].dt; new_arr[i].dt = new_arr[j].dt; new_arr[j].dt = min_dt; // 顺便把dt 和 obj也排序 min_zt = new_arr[i].zt; new_arr[i].zt = new_arr[j].zt; new_arr[j].zt = min_zt; min_obj = new_arr[i].obj; new_arr[i].obj = new_arr[j].obj; new_arr[j].obj = min_obj; } } } console.log("排序后new_arr:", new_arr); // 增加 - 号 let newarr2 = []; new_arr.forEach(function (item) { let item1 = item.dt; item1 = item1.toString(); console.log("item:", item1); let temp; let temp1 = item1.substring(0, 4); let temp2 = item1.substring(4, 6); let temp3 = item1.substring(6, 8); temp = temp1.concat('-',temp2 , '-', temp3 ); console.log("temp:", temp); newarr2.push({ zt: item.zt, obj: item.obj, dt: temp }) }); console.log("2号新数组newarr2:", newarr2); // 重新渲染 for (var i = 0; i < this.menu.length; i++) { this.menu[i].dt = newarr2[i].dt; this.menu[i].zt = newarr2[i].zt; this.menu[i].obj = newarr2[i].obj; } } } } </script>
<style> .wrapper { width: 100%; height: 600upx; background-color: #F7F7F7; } .main { width: 800upx; height: 80upx; display: flex; flex: column; } .obj { width: 600upx; height: 60upx; background-color: #D9D9D9; } .zt { width: 200upx; height: 60upx; background-color: #D4D4D4; } </style>
排序后结果如下: