Vue implements element dragging and swapping positions

Project scenario:

In the scenario where Vue is used, elements need to be dragged and swapped.

Insert image description here


demand analysis:

1. What is exchanged in pairs is actually the subscript of the array. The data content remains unchanged.
2. The drag and drop function requires the use of API.

method name Detailed explanation
ondraggable Sets whether the element is allowed to be dragged. Links and images are draggable by default, so there is no need to set this property.
ondragstart Fired when the user starts dragging an element or selected text.
ondragover Fires when the dragged element or selected text is being dragged to the drop target.
By default, data/elements cannot be placed inside other elements.
If we want to implement the change function, we need to prevent the default processing method of the element.
We can implement the ondragover event by calling the event.preventDefault() method.
ondragenter This event is triggered when the object being dragged by the mouse enters its container.
ondragend Fires after the user completes dragging the element

For more API introductions, you can read Click here


Code:

<table>
	<thead>
		<tr>
			<th>标题1</th>
			<th>标题2</th>
			<th>标题3</th>
		</tr>
	</thead>
	<tbody>
		<tr v-for="(items,index) in dataList" :key="index"
			draggable="true"
            @dragstart="handleDragStart($event, items)"
            @dragover.prevent="handleDragOver($event, items)"
            @dragenter="handleDragEnter($event, items)"
            @dragend="handleDragEnd($event, items)"
        >
			<td>{
   
   {items.content}}</td>
		</tr>
	</tbody>
</table>

<script>
	var VM = new Vue({
      
      
		el:'#app',
		data:function(){
      
      
			return {
      
      
				dataList:[{
      
      
					content:'内容'
				},{
      
      
					content:'内容'
				},{
      
      
					content:'内容'
				}],
				dragging: null
			}
		},
		methods:{
      
      
			handleDragStart(e,items){
      
      
                this.dragging = items;//开始拖动时,暂时保存当前拖动的数据。
            },
            handleDragEnd(e,items){
      
      
                this.dragging = null;//拖动结束后,清除数据
            },
            handleDragOver(e) {
      
      
                e.dataTransfer.dropEffect = 'move';//在dragenter中针对放置目标来设置!
            },
            handleDragEnter(e,items){
      
      
                e.dataTransfer.effectAllowed = "move";//为需要移动的元素设置dragstart事件
                if(items == this.dragging) return;
                var newItems = [...this.dataList];//拷贝一份数据进行交换操作。
                var src = newItems.indexOf(this.dragging);//获取数组下标
                var dst = newItems.indexOf(items);
                newItems.splice(dst, 0, ...newItems.splice(src, 1));//交换位置
                this.dataList = newItems;
            }
		}
	})
</script>

关于Array.prototype.splice()

Guess you like

Origin blog.csdn.net/weixin_41535944/article/details/119205672