sortBy(逆序排序)的使用
核心代码:根据status,upload_time逆序排列,优先级status>upload_timethis.list= sortBy(this.list, [‘status’,‘upload_time’]).reverse()index.vue<script>import { sortBy } from 'lodash'export default {data () {ret
·
核心代码:
根据status,upload_time逆序排列,优先级status>upload_time
this.list= sortBy(this.list, [‘status’,‘upload_time’]).reverse()
index.vue
<script>
import { sortBy } from 'lodash'
export default {
data () {
return {
list: [
{
upload_time: "2021-08-03 12:00:02",
name: "xxx1",
status: 0
},
{
upload_time: "2021-08-03 12:00:02",
name: "xxx2",
status: 1
},
{
upload_time: "2021-08-03 12:00:02",
name: "xxx3",
status: 0
},
{
upload_time: "2016-05-02 14:00:02",
name: "xxx4",
status: 1
}
]
}
},
// 过滤器,对status为0的显示正常,否则显示异常。
filters: {
getWarningState: (value) => {
return value === 0 ? "正常" : "异常";
}
},
mounted(){
console.log(this.list)
this.list= sortBy(this.list, ['status','upload_time']).reverse()
console.log(this.list)
}
}
</script>
如果传过来的status是字符串true/false,“false"代表异常,那么比较"false”<“true”
此时我们先把时间逆序排好,然后正序排列status字段。
this.list = sortBy(sortBy(this.list, ['upload_time']).reverse(), 'status')
扩展:
查资料发现还有以下几种方式排序
- this.list.sortByOrder(this.list, [‘status’,‘upload_time’], [false, false]) // lodash版本3.5.0
- this.list.sortByOrder(this.list, [‘status’,‘upload_time’], [‘asc’, ‘desc’]) // lodash版本3.10.0
- this.list.orderBy(this.list, [‘status’,‘upload_time’], [‘asc’, ‘desc’]) // lodash版本4.3.0重定义
- this.list.sort(function(a, b) {
return a.status- b.status// desc
|| +(b.upload_time>a.upload_time)||-(a.upload_time>b.upload_time) // desc
|| …;
})- this.list.each(this.list, function(o) {
o.typeDesc = -o.status;
});- this.list.chain().sort(“upload_time”).reverse() // sort by upload_time 降序
.sort(“status”) // sort by status 升序
.result()
下列是个排序的组件template里的,可以忽略。我给自己看的。
<el-dropdown @command="onSortChange">
<div class="sort-type">
<span class="sort-text" :title="sorts[sort]">{{ sorts[sort] }}</span
><i class="el-icon-arrow-down arrow-icon"></i>
</div>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item
v-for="(value, key) in sorts"
:key="key"
:command="key"
>{{ value }}</el-dropdown-item
>
</el-dropdown-menu>
</el-dropdown>
---------------------------------------------------------------------
sort: 'status',
sorts: {
status: '按异常状态排序',
upload_time: '按上传时间排序'
}
onSortChange (val) {
this.sort = val
}
---------------------------------------------------------------------
.sort-type {
display: inline-block;
color: #bcc9d4;
line-height: 30px;
cursor: pointer;
font-size: 14px;
min-width: 100px;
.arrow-icon {
font-size: 14px;
margin-left: 4px;
}
&:hover {
color: #2681ff;
}
}
更多推荐
已为社区贡献6条内容
所有评论(0)