vue下使用sortablejs

在不变动后端返回的数据的条件下,实现排序并保存,这里自然而然就想到了使用计算属性。
额外设置了一个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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值