Error in directive sortable bind hook: “TypeError: Sortable is not a constructor – Vuejs

The code is so simple to fix issue, just put this shit into your project and get it work for Vue 2:

Install dependency of SortableJs

import Vue from 'vue'
import Sortable from 'sortablejs'

Vue.directive('sortable', {
  inserted: function (el, binding) {
    new Sortable(el, binding.value || {})
  }
})

Create sortable directive and used like this:

<ul v-sortable="{onEnd: reorder}">
    <li v-for="i in items" :key="i.id">{{ i.id }}</li>
  </ul>

Full example code here:

<div id="app">
  <ul v-sortable="{onEnd: reorder}">
    <li v-for="i in items" :key="i.id">{{ i.id }}</li>
  </ul>
  {{ items | json }}
</div>
Vue.directive('sortable', {
  inserted: function (el, binding) {
    var sortable = new Sortable(el, binding.value || {});
  }
});

new Vue({
	el: '#app',
	data () {
  	return {
    	items: [{id: 1},{id: 2},{id: 3},{id: 4},{id: 5}]
    }
  },
  methods: {
  	reorder ({oldIndex, newIndex}) {
    	const movedItem = this.items.splice(oldIndex, 1)[0]
      this.items.splice(newIndex, 0, movedItem)
    }
  }
})

 

Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Yes4
No0
Harinder Singh

Harinder Singh

My name is Harinder Singh and I specialize in Software industry. I consider myself as a life learner. I love learning new concepts, embracing new ideas and reading and searching for innovation.