在不变动后端返回的数据的条件下,实现排序并保存,这里自然而然就想到了使用计算属性。
额外设置了一个map存储数据与排序的关系。最后在计算属性返回时计算排序,并在每次发生拖拽的时候记录新的排序
这里感觉排序的方法做的比较蠢,有待优化
另外排序也只暂存在localStorage里面了。其实可以存后端。
<template>
<div>
<div id="table-names">
<span v-for="item of sortedTable" :key="item.id">{{ item.name }}</span>
</div>
</div>
</template>
<script>
import Sortable from 'sortablejs'
export default {
data(){
return{
tableData:[
{name: 'laowang1', id: '1'},
{name: 'laowang2', id: '2'},
{name: 'laowang3', id: '3'},
{name: 'laowang4', id: '4'},
],
sortMap: new Map
}
},
computed: {
sortedTable(){
if(this.sortMap.size > 0){
let list = [];
this.tableData.forEach(item => {
let sort = this.sortMap.get(item.id);
list.push({...item, sort})
})
list = list.sort((a, b) =>{
return a.sort - b.sort;
})
return list;
} else {
return this.tableData;
}
}
},
mounted(){
this.initMap();
this.dragTable();
},
methods:{
initMap(){
this.sortMap = new Map(Object.entries(JSON.parse(localStorage.getItem('sortMap'))))
if(this.sortMap == null || this.sortMap.size == 0){
this.sortMap = new Map;
for(let i = 0; i < this.tableData.length; i++){
this.sortMap.set(this.tableData[i].id, i)
}
}
},
switchMapOrder(oldIndex, newIndex){
let preId = null;
let currId = null;
this.sortMap.forEach((value, key) => {
let idSort = value;
if(idSort == oldIndex || idSort == newIndex){
if(preId == null){
preId = key;
} else {
currId = key;
}
}
})
let preSort = this.sortMap.get(preId);
let currSort = this.sortMap.get(currId);
this.sortMap.set(preId, currSort)
this.sortMap.set(currId, preSort)
let sortMapStr = JSON.stringify(Object.fromEntries(this.sortMap))
localStorage.setItem('sortMap', sortMapStr);
},
dragTable(){
let el = document.getElementById('table-names');
Sortable.create(el, {
animation: 300,
onEnd: evt => {
let oldIndex = evt.oldIndex;
let newIndex = evt.newIndex;
this.switchMapOrder(oldIndex, newIndex);
}
})
}
}
}
</script>
<style>
#table-names {
display: flex;
flex-direction: column;
}
</style>