javascriptvue.jsdrag-and-dropsmartphone

move items while dragging even on smartphones


Hi everyone I'm trying to move items while dragging on smartphone as well

My HTML code:

 <input class="inputText mb-2 border border-primary rounded" v-model="newTodo" 
 @keypress.13='addTodo' placeholder="Scrivi qualcosa"> 
 <button class="btn btn-info" @click="addTodo">
   <i class="far fa-paper-plane"></i>
 </button> 

 <ul class="col-12">
  <div v-for="(todo, n) in todos" draggable="true" @dragstart="dragStart(n, $event)" 
   @dragover.prevent  @dragend="dragEnd" @drop="dragFinish(n, $event)">
   <li class="mt-2 todo">
      anvedi come balla nando   {{ todo.name }}
   </li> 
  </div>
 </ul>

My JS code:

 const app = new Vue({
   el: '#app',
    data: {
     todos: [{}],
     dragging: -1,
    },
   mounted() {
     if (localStorage.getItem('todos') && localStorage.getItem('list')) {
       try {
         this.todos = JSON.parse(localStorage.getItem('todos')); 
         this.list = JSON.parse(localStorage.getItem('list')); 
       } catch (e) {
         localStorage.removeItem('todos'); 
         localStorage.removeItem('list');
       }
     }
   },
    methods: {
     addTodo() {
       if (!this.newTodo) {
         return;
       }
       this.todos.push({
         name: this.newTodo,
         isHidden: true,
         isActive: false,
       });
       this.list.push(this.newTodo + '\n'); 
       this.newTodo = ''; 
       this.saveTodos(); 
     },
     dragStart(which, ev) {
       ev.dataTransfer.setData('Text', this.id);
       ev.dataTransfer.dropEffect = 'move';
       this.dragging = which;
     },
     dragEnd(ev) {
       this.dragging = -1;
     },
     dragFinish(to, ev) {
       this.moveItem(this.dragging, to);
       ev.target.style.marginTop = '2px';
       ev.target.style.marginBottom = '2px';
     },
     moveItem(from, to) {
       if (to === -1) {
         this.removeItemAt(from);
       } else {
         this.todos.splice(to, 0, this.todos.splice(from, 1)[0]);
       }
     },
   },
   computed: {
     isDragging() {
       return this.dragging > -1;
     },
   },
 });

On a pc it works perfectly, but trying it on a smartphone doesn't work.....

I think more detailed than that I can't do it, but stack forces me to write more words because I have written too much code and too little text, but I don't think there is much more to say, the question is clear and simple, and the code too!


Solution

  • I had the same problem in a project at work. I didn't manage to solve it just with VueJs, but I used the vue2-touch-event package, as well as the interact.js library for more precise control over some DOM elements. I'd recommend vue2-touch-event if you don't want to have to modify your code too much.