DEV Community

Cover image for Simple sortable list with VueJS
Shuvo
Shuvo

Posted on

Simple sortable list with VueJS

In this article we are going to create a simple sortable list using Vue JS.(However you would like to create an advanced project like shown in the cover photo you can follow this VueJS tutorial series that I have started.)

Okay lets start by using v-for directive to create a simple list.

<template>
  <div id="container">
    <div class="todo" v-for="todo in todos" :key="todo">
      <span>{{todo}}</span>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data: () => ({
    todos: [
      "Item 1",
      "item 3",
      "Item 3",
      "Item 4",
      "Item 5"
    ]
  })
}
</script>

<style>
/*Your CSS goes here*/
</style>
Enter fullscreen mode Exit fullscreen mode

The output should look something like this
Vue List Demo
But the list is not sortable so let make is sortable now. To do that we are going to use Vue.Draggable so install it by running npm i vuedraggable.
Now you can import it and use it like a component.
So to make our list sortable we simply have to wrap our list with draggable and we also have to use our todos for its v-model

<template>
  <div id="container">
    <draggable v-model="todos">
      <div class="todo" v-for="todo in todos" :key="todo">
        <span>{{todo}}</span>
      </div>
    </draggable>
  </div>
</template>

<script>
import draggable from 'vuedraggable'

export default {
  name: "App",
  components: {
    draggable
  },
  data: () => ({
    todos: [
      "Item 1",
      "item 3",
      "Item 3",
      "Item 4",
      "Item 5"
    ]
  })
}
</script>
Enter fullscreen mode Exit fullscreen mode

Now you will se you can now drag your todos to sort them
Vue list sort
Also If you want you can specify a handle for sorting(the element that you will drag to sort the list)

<template>
  <div id="container">
    <draggable v-model="todos" handle=".handle">
      <div class="todo" v-for="todo in todos" :key="todo">
        <span class="handle">&#8597;</span>
        <span>{{todo}}</span>
      </div>
    </draggable>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

Vue list sort with handle

Finally You can use transition-group to add some animation

<template>
  <div id="container">
    <draggable v-model="todos" handle=".handle">
      <transition-group name="list">
        <div class="todo" v-for="todo in todos" :key="todo">
          <span class="handle">&#8597;</span>
          <span>{{todo}}</span>
        </div>
      </transition-group>
    </draggable>
  </div>
</template>

<style>
.list-move{
  transition: .5s;
}
</style>
Enter fullscreen mode Exit fullscreen mode

So now if you try to sort your todos you will see they animates their position.

That's all for now and Thanks for reading. Be sure to check out my other articles and My YouTube Channel

Discussion (0)