Home > Blockchain >  How to implement html drag and drop using vue 3 composition API
How to implement html drag and drop using vue 3 composition API

Time:11-24

currently drag and drop feature is working with vue2, i want to achieve same feature using vue3 composition api.

vue2 code:

<div id="app">
  <div id="box-droppable1" @drop="drop" @dragover="allowDrop">
    <h3>Draggaable area 1:</h3>
    <hr>
    
    <div  draggable="true" @dragstart="onDragging" id="123">
      <h2>Drag mee</h2>
      <p>this is a text</p>
    </div>
     
    <img id="img-draggable" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" draggable="true" @dragstart="drag" width="336">
  </div>
  
  <div id="box-droppable2" @drop="drop" @dragover="allowDrop">
    <h3>Droppable area 2:</h3>
    <hr>
  </div>
</div>

Here is vuejs code done using vuejs options API.

JS:

new Vue({
  el: '#app',
  data(){
    return {
    };
  },
  methods : {
    onDragging(ev){
      console.log(ev);
      ev.dataTransfer.setData("text", ev.target.id);
      //this.$store.commit('module/namespace', status);
    },
    allowDrop(ev) {
      ev.preventDefault();
    },
    drag(ev) {
      ev.dataTransfer.setData("text", ev.target.id);
    },
    drop(ev) {
      ev.preventDefault();
      let data = ev.dataTransfer.getData("text");
      console.log(data);
      ev.target.appendChild(document.getElementById(data));
    }
  },
})

css:

#app{
  width: 100%;
  display: flex;
  
  #box-droppable1 {
    width: 50%;
    background-color: coral;
    min-height: 300px;
    height: 70px;
    
    padding: 10px;
    border: 1px  solid #aaaaaa;
  }
  
  #box-droppable2 {
    width: 50%;
    min-height: 300px;
    height: 70px;
    padding: 10px;
    border: 1px solid #aaaaaa;
  }
}

---------------------#---------------------------------------------------------------------------------------#------------------

codepen

CodePudding user response:

As the comments already mention, this is nothing that would be different in the composition API, which is just another way to define a component.

All the methods you have in the options API, you can just have them in the setup method and return them:

setup() {
    const onDragging = (ev) => {
        console.log(ev);
        ev.dataTransfer.setData("text", ev.target.id);
    };
    const allowDrop = (ev) => {
        ev.preventDefault();
    };
    const drag = (ev) => {
        ev.dataTransfer.setData("text", ev.target.id);
    };
    const drop = (ev) => {
        ev.preventDefault();
        let data = ev.dataTransfer.getData("text");
        console.log(data);
        ev.target.appendChild(document.getElementById(data));
    }
    return {
        onDragging,
        allowDrop,
        drag,
        drop,
    }
}

I would probably not directly append a child with vanila js but also do it the Vue way, but that's just a side note.

  • Related