Created
June 1, 2018 08:29
-
-
Save onefriendaday/78f51587115b402563efb5b739d61b51 to your computer and use it in GitHub Desktop.
sortable directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Sortable = require('sortablejs') | |
module.exports = { | |
update: function (val) { | |
var self = this | |
this.sortable = Sortable.create(this.el, { | |
animation: 150, | |
handle: '.sortable__handle', | |
onStart: function (e) { | |
jQuery(e.target).closest('.sortable').addClass('sortable--sorting') | |
}, | |
onEnd: function (e) { | |
jQuery(e.target).closest('.sortable').removeClass('sortable--sorting') | |
var obj = self.vm.$get(val.key) | |
var clone = null | |
if (obj.constructor === Object) { | |
self.vm.$set(val.key, {}) | |
var keys = Object.keys(obj) | |
var newObj = {} | |
var swappedEl = keys.splice(e.item.dataset.index, 1)[0] | |
keys.splice(e.newIndex, 0, swappedEl) | |
keys.forEach(function(key) { | |
newObj[key] = obj[key] | |
}) | |
clone = newObj | |
} else { | |
// Clone container | |
clone = JSON.parse(JSON.stringify(obj)) | |
self.vm.$set(val.key, []) | |
// Move to new position | |
var swappedEl = clone.splice(e.item.dataset.index, 1)[0] | |
clone.splice(e.newIndex, 0, swappedEl) | |
} | |
// On next Tick update with clone | |
self.vm.$nextTick(function() { | |
self.vm.$set(val.key, clone) | |
self.vm.$emit('sorted', {position: e.newIndex + 1, id: e.item.dataset.id}) | |
}) | |
} | |
}) | |
}, | |
unbind: function() { | |
this.sortable.destroy() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment