If you are not familiar with some of the features of the H5 drag API, please go to ->

Github source address

Nuggets talk about h5 drag a post


Due to the requirements of the project, we need to implement a drag and drop component, which is a component based on HTML5. The function of H5 is relatively perfect. Because it is still in the demo stage, there is no customization function at present, but only exchange function

Directory structure:

Arrows are our components

The demo code:

Component source code

<template> <div class="contain" :id="`drag`+index" :ref="`drag`+index" draggable="true" v-on:dragstart="handle_dragstart" v-on:drag="handle_drag" v-on:drop="handle_ondrop" v-on:dragover="allowDrop" > <slot></slot> </div> </template> <script> export default { data() { return {}; }, // Props: {index: {type: Number, required: true}}, methods: SwapElements (a, b) {// Exchange two DOM elements if (a == b) return; Var bp = b.parentNode, ap = a.parentnode; Var an = a.sibling, bn = b.sibling; If (an == b) return bp.insertbefore (b, a); if (bn == a) return ap.insertBefore(a, b); If (a.taintains (b)) // return ap.insertbefore (b, a), bp.insertbefore (a, bn); else return bp.insertBefore(a, b), ap.insertBefore(b, an); }, handle_dragstart(ev) { ev.dataTransfer.setData("dragDom", ev.target.id); }, handle_drag() {console.log("drag- repeatedly triggered at the start of an element "); }, handle_dragend() {console.log("dragend- triggered when the drag operation is complete "); }, allowDrop(ev) { ev.preventDefault(); }, handle_ondrop(event) { let data = event.dataTransfer.getData("dragDom"); Console. log(document.getelementById (data), event. Target, "These two DOM "); this.swapElements(document.getElementById(data), event.currentTarget); Console. log(event.target, "dragend- triggered when dropped "); }, dragInit() {} }, components: {}, mounted() { this.dragInit(); }}; </script> <style> .contain{ cursor: pointer; } </style>Copy the code

The demo code

<template> <div class="box"> <dragAndDrop class="contain" v-for="(item, index) in arr" :key="index" :index='index' > {{index}} </dragAndDrop> </div> </template> <script> import dragAndDrop from "./dragAndDrop"; export default { data() { return { arr: [] }; }, methods: { }, components: { dragAndDrop }, mounted() { this.arr = new Array(9).fill(null); // this.dragInit(); }}; </script> <style> .box { display: flex; flex-wrap: wrap; } .contain { width: 200px; height: 200px; background: purple; margin: 20px; font-size: 40px; } </style>Copy the code