dragula插件实现拖拽

本文介绍了一种使用dragula插件实现拖拽排序的方法,通过JavaScript代码详细展示了如何为UI组件添加拖拽效果,包括镜像元素的样式控制及元素排序后的数据更新策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 拖拽
  • 拖拽加效果
  • 排序

拖拽

使用插件: https://github.com/bevacqua/dragula

dragulaDecorator = componentBackingInstance => {
  if (componentBackingInstance) {
    let options = {
      revertOnSpill: true, // 溢出会将元素放回到被拖动的位置
      mirrorContainer: document.body // 设置获取镜像元素的元素
      // moves: function (el, source, handle, sibling) {
      //     return true; // 元素默认是可拖动的 可设置预期的拖动元素
      // }
    };

    Dragula([componentBackingInstance], options)
      .on("drag", el => {
        options.mirrorContainer = el;
      })
      .on("dragend", el => {})
      .on("drop", (el, target, source, sibling) => {
        // 只有顺序改变时才会触发该方法 sibling没有值,代表是移动了最后一个位置。
        this.props.TicketForm.changeFieldSort(
          el.dataset.id,
          sibling.dataset.id
        );
        // if(sibling){

        // }else{
        //     console.log("我是最后一个");
        // }
        // console.log(toJS(this.props.TicketForm.formFileds));
      });
  }
};
<div className="dragula-container" ref={this.dragulaDecorator} />;

拖动加效果

// 在拖动时,gu-unselectable被添加到mirrorContainer元素。 您可以使用它来在正在拖动某个东西的情况下设置mirrorContainer的样式。
.gu-unselectable {
  -webkit-user-select: none !important;
  -moz-user-select: none !important;
  -ms-user-select: none !important;
  user-select: none !important;
  // background-color: #fff;
}
// 当它的镜像被拖拽时,gu-transit被添加到源元素中。 它只是增加了不透明度。
.gu-transit {
  opacity: 0.2;
  padding: 10px 0;
  border: 2px dashed;
  // background-color: rgba(0, 0, 0, 0.2);
  // transition: opacity 0.4s ease-in-out;
  // -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";
  // filter: alpha(opacity=20);
}

// 镜像被添加到镜像中。 它处理固定位置和z-index(并删除元素上的任何先前边距)。
.gu-mirror {
  padding: 10px 0;
  // box-sizing: content-box;
  background-color: rgba(0, 0, 0, 0.3);
  border: 2px dashed;
  transition: opacity 0.4s ease-in-out;
  position: fixed !important;
  margin: 0 !important;
  z-index: 9999 !important;
  cursor: grabbing;
  cursor: -moz-grabbing;
  cursor: -webkit-grabbing;
}

.gu-hide {
  display: none !important;
}

获取排序之后的顺序

先根据index作为序号,拖拽元素位置更改后 ,删除源数据,再把源数据插入到目标位置,然后重新排序。

store 中的代码:

// 管理排序
@action initFieldSort = () => {
  this.formFileds.map((item,index)=>{
    // 解决  对象更新 而 页面上的信息没有随之更新 的bug 
    // 原因:formFileds 更新了,但是却没有监听到item的改变,所以使用到item的数据没有发生变化
    let obj = JSON.parse(JSON.stringify(item));
    obj.sort = index;
    item = obj;
  });
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值