Vue使用sortablejs拖拽排序 视图显示与数据不一致、拖拽结束后回跳问题解决方案

Vue项目中使用sortable实现对块元素拖拽进行排序,sortable.js是一款很好用的拖拽插件,最近尝试用它做一个列表卡片拖拽功能。但是它是直接操作DOM的类库,如果有其他数据驱动类型的类库,建议不优先考虑。

一、安装

npm install sortablejs --save

二、引入:

import Sortable from ‘sortablejs’

三、使用

<section class="section-module" v-for="(element, index) in moduleList" :key="index">
... ...
</section>

<script>
import Sortable from 'sortablejs'

export default {
  mounted(){
    let that = this;
    new Sortable(document.getElementById('module'), {
      animation: 1000,
      ghostClass: 'sortable-ghost',
      onEnd: function (evt) {
        
        // 拖拽排序数据
        that.moduleList.splice(evt.newIndex, 0, that.moduleList.splice(evt.oldIndex, 1)[0])
        const newArray = that.moduleList.slice(0)
        
        // 重新赋值来刷新视图 (这里我调的父组件的变量,你的可以换成当前组件的变量)
        that.$parent.moduleList = [] // 必须有此步骤,不然拖拽后回弹
        that.$nextTick(function () {
          that.$parent.moduleList = newArray // 重新赋值,用新数据来刷新视图 
          console.log(that.moduleList)
        })
      }
    });
  },
}
</script>

四、问题与解决方案

如果遇到数据不一致、拖拽结束后回跳如何解决

 上边代码注释里已经写了解决方法,也许你的情况和我的不一样,注意分析问题的原理最关键。

看看其他博主遇到的问题:https://blog.csdn.net/u012169390/article/details/101280523

 或许能给你点启示。

五、总结

sortablejs 是基于dom操作的,Vue的数据驱动,再直接操作DOM的情况下,会出现各种显示不一致问题,可以用 that.$parent.moduleList = [],vue的相关方法去重新更新,来解决该问题。

猜你喜欢

转载自blog.csdn.net/meimeieee/article/details/127928006