<template>
<div :class="$options.name">
<ul>
<li v-for="(a, i) in items" :key="i">
<span v-if="a.topIndex">当前置顶索引topIndex:{{ a.topIndex }}</span>
<span>当前索引index:{{ a.index }}</span>
<label>{{ a.label }}</label>
<el-button v-if="a.topIndex" type="danger" plain @click="unTop(a)">取消置顶</el-button>
<el-button v-else type="primary" plain @click="top(a)">置顶</el-button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
topIndex: 0,//置顶索引
items: [
{ index: 1, label: '显示文本1', },
{ index: 2, label: '显示文本2', },
{ index: 3, label: '显示文本3', },
{ index: 4, label: '显示文本4', },
{ index: 5, label: '显示文本5', },
]
}
},
methods: {
// 对置顶列表进行排序计算
sortTopList(arr) {
arr = JSON.parse(JSON.stringify(arr));
let tops = arr.filter(v => v.topIndex);//筛选出置顶项目
let upTops = arr.filter(v => !v.topIndex);//帅选出未置顶项目
tops.sort((prev, next) => prev.topIndex - next.topIndex);//从小到大升序
upTops.sort((prev, next) => prev.index - next.index);//从小到大升序
return JSON.parse(JSON.stringify(tops.concat(upTops)));
},
//置顶
top(d) {
d.topIndex = --this.topIndex;
this.items = this.sortTopList(this.items);
},
//取消置顶
unTop(d) {
delete d.topIndex;
this.items = this.sortTopList(this.items);
},
}
};
</script>
排序置顶、非置顶算法,实现置顶后的结果和非置顶的内容排序保持原始序列
于 2023-07-28 12:59:16 首次发布