其他分享
首页 > 其他分享> > VUE 实现拖拽排序(前后端)

VUE 实现拖拽排序(前后端)

作者:互联网

需求:横向排列的测试01、测试02、测试03需要拖拽排序 

主要思路:前端通过鼠标按住某一项拖拽排序,tabList会重新排序得到新数组,遍历新数组获取id得到排序的id数组,调用后端接口,后端根据排序的idList更新数据库的orderNum序号字段。

在拖动目标上触发事件 (源元素):

释放目标时触发的事件:

前端:

<div
  v-for="(item,index) in tabList"
  :key="index"
  class="tab-item"
  :class="currentTab === item.id ? 'activeTab':''"
  :draggable="true"
  @dragstart="dragstart(item)"
  @dragenter="dragenter(item,$event)"
  @dragend="dragend(item,$event)"
  @dragover="dragover($event)"
  @click="handleChangeTab(item.id, true)"
>
  <span>{{ item.collectionName }}</span>
</div>
//拖拽排序前的数组
dragstart(value) {
  this.oldData = value
},
//拖拽排序后的数组
dragenter(value, e) {
  this.newData = value
  e.preventDefault()
},
//拖拽最后操作
dragend(value, e) {
  if (this.oldData !== this.newData) {
    const oldIndex = this.tabList.indexOf(this.oldData)
    const newIndex = this.tabList.indexOf(this.newData)
    const newItems = [...this.tabList]
    newItems.splice(oldIndex, 1)
    newItems.splice(newIndex, 0, this.oldData)
    this.tabList = [...newItems]
    const idList = []
    this.tabList.forEach((value, index) => {
      idList.push(value.id)
    })
    //后台更新序号
    this.apiRefreshCollectionOrderNum({
      packageId: this.packageId,
      idList: idList
    }).then(res => {
      const { success, message } = res
      if (success) {
        this.$message({
          message: message,
          type: 'success'
        })
      }
    })
  }
},
// 拖动事件(主要是为了拖动时鼠标光标不变为禁止)
dragover(e) {
  e.preventDefault()
}

 

 

后端: sql直接更新

StringBuilder sb = new StringBuilder("update table bc set bc.order_num = case bc.id ");
for (int i = 0; i < idList.size(); i++) {
    sb.append(" when ");
    sb.append(idList.get(i));
    sb.append(" then ");
    sb.append(i + 1);
}
sb.append(" end where bc.id in(:ids)");
Session session = entityManager.unwrap(Session.class);
NativeQuery query = session.createSQLQuery(sb.toString());
query.setParameter("ids", idList);

 

标签:触发,VUE,idList,拖动,value,sb,排序,拖拽
来源: https://blog.csdn.net/m0_50304006/article/details/120765951