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>
The output should look something like this
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>
Now you will se you can now drag your todos to sort them
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">↕</span>
<span>{{todo}}</span>
</div>
</draggable>
</div>
</template>
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">↕</span>
<span>{{todo}}</span>
</div>
</transition-group>
</draggable>
</div>
</template>
<style>
.list-move{
transition: .5s;
}
</style>
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
Top comments (0)