Categories
JavaScript Vue

Add Drag and Drop into a Vuejs App

Spread the love

We can add basic drag and drop features into a Vue app.

The vuedraggable library makes adding drag and drop easy.

To use it, first we install it by running:

npm i -S vuedraggable

Then we can use it as follows:

App.vue

<template>
  <div id="app">
    <draggable group="words" :list="arr" @change="log">
      <div v-for="element in arr" :key="element">{{element}}</div>
    </draggable>
  </div>
</template>

<script>
import draggable from "vuedraggable";

export default {
  name: "App",
  components: {
    draggable
  },
  data() {
    return {
      arr: ['item1', 'item2', 'item3']
    };
  },
  methods: {
    log(e) {
      console.log(e);
    }
  }
};
</script>

We add the draggable component to the App component and we can display a list where we can drag them items around the way we wish to.

As we drag and drop the items, we log the changed with the log method, which has the element that’s been moved and the original and new index of the item.

We can also add headers or footers by using the slots as follows:

App.vue

<template>
  <div id="app">
    <draggable group="words" :list="arr" @change="log">
      <div v-for="element in arr" :key="element">{{element}}</div>
      <button slot="footer" @click="addItem">Add</button>
    </draggable>
  </div>
</template>

<script>
import draggable from "vuedraggable";

export default {
  name: "App",
  components: {
    draggable
  },
  data() {
    return {
      arr: ["item1", "item2", "item3"]
    };
  },
  methods: {
    log(e) {
      console.log(e);
    },
    addItem() {
      this.arr = [...this.arr, `item${this.arr.length + 1}`];
    }
  }
};
</script>

We added a button by writing:

<button slot="footer" @click="addItem">Add</button>

As long as the slot’s value is footer, it’ll be displayed below the list.

If we change the slot’s value to header, then it’ll displayed on top of the list:

<template>
  <div id="app">
    <draggable group="words" :list="arr" @change="log">
      <button slot="header" @click="addItem">Add</button>
      <div v-for="element in arr" :key="element">{{element}}</div>
    </draggable>
  </div>
</template>

<script>
import draggable from "vuedraggable";

export default {
  name: "App",
  components: {
    draggable
  },
  data() {
    return {
      arr: ["item1", "item2", "item3"]
    };
  },
  methods: {
    log(e) {
      console.log(e);
    },
    addItem() {
      this.arr = [...this.arr, `item${this.arr.length + 1}`];
    }
  }
};
</script>

vuedraggable is very useful for creating drag and drop lists with ease.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *