Vue2+elementui表格实现拖拽行功能

步骤一:安装 sortablejs 依赖 npm install sortablejs --save

npm install sortablejs --save

步骤二:基础表格代码

 
            
            
            
            
            
              
            
            
              
            
          

效果图:

Vue2+elementui表格实现拖拽行功能_第1张图片

其中最重要的是

Vue2+elementui表格实现拖拽行功能_第2张图片

row-key='id'得加上,不然会出现回弹或者排序错乱的情况,这个id必须是唯一的,指的是每一行的id都是唯一且不会重复的,若没有id可以用Math.round()随机数去代替减少重复率,

步骤三,引入下载好的依赖

import Sortable from "sortablejs";

 
data(){ 
form:{
 manufacturing: [
          {
            keys: Math.random().toFixed(4),
            name: "",
            id: "",
          },
        ],
    }
}

步骤四:找到表格dom元素(指的是要拖拽元素的父容器)

 rowDrop() {
      const tbody = this.$refs.manufacturing.$el.querySelector(
        ".el-table__body-wrapper > table > tbody"
      );
      const _this = this;
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.form.manufacturing.splice(oldIndex, 1)[0];
          _this.form.manufacturing.splice(newIndex, 0, currRow);
        },
      });
}

步骤五,在挂载完成生命周期去触发这个事件

 mounted() {
    this.$nextTick(() => {
      this.rowDrop();
    });
  },

完成以上五步基本就可以实现了,若是不行欢迎留言

你可能感兴趣的:(elementui知识,elementui,vue.js,javascript)