拖放后重置所有项目的Vue.js列表顺序

Jac*_*ham 4 javascript drag-and-drop jquery-ui-sortable vue.js

我有一个拖放组件(使用Sortable),但是一旦将项目放到新位置后就无法弄清楚更新列表顺序的逻辑。

代码(Vue.js):

new Vue({
  el: '#app',
  template: '#dragdrop',
  data() {
    return {
      list: [
        {name: 'Item 1', id: 1, order: 0}, 
        {name: 'Item 2', id: 2, order: 1}, 
        {name: 'Item 3', id: 3, order: 2}, 
        {name: 'Item 4', id: 4, order: 3}, 
        {name: 'Item 5', id: 5, order: 4}, 
        {name: 'Item 6', id: 5, order: 5}, 
       ],
    }
  },
  ready() {
    Sortable.create(document.getElementById('sort'), {
      draggable: 'li.sort-item',
      ghostClass: "sort-ghost",
      animation: 80,
      onUpdate: function(evt) {
        console.log('dropped (Sortable)');
      }
    });
  },
  methods: {
    dropped() {
      console.log('dropped (Vue method)');
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

我有一个正在工作的JSFiddle:https ://jsfiddle.net/jackbarham/rubagbc5

我正在寻找要order同步的数组,以便一旦删除该项目就可以进行AJAX更新。

Pet*_*ter 5

这不是最优雅的解决方案,但我认为它可行。这使用Sortable onUpdate处理程序更新基础数组。每当将项目拖动到新位置时,它都会移动到数组中的同一位置-这样,视图模型将与视图中显示的内容保持同步。然后,项order属性将更新以匹配其在数组中的新位置。

new Vue({
  el: '#app',
  template: '#dragdrop',
  data() {
    return {
      list: [
        {name: 'Item 1', id: 1, order: 0}, 
        {name: 'Item 2', id: 2, order: 1}, 
        {name: 'Item 3', id: 3, order: 2}, 
        {name: 'Item 4', id: 4, order: 3}, 
        {name: 'Item 5', id: 5, order: 4}, 
        {name: 'Item 6', id: 6, order: 5}, 
       ],
    }
  },
  ready() {
    var vm = this;
    Sortable.create(document.getElementById('sort'), {
      draggable: 'li.sort-item',
      ghostClass: "sort-ghost",
      animation: 80,
      onUpdate: function(evt) {
        console.log('dropped (Sortable)');
        vm.reorder(evt.oldIndex, evt.newIndex);
      }
    });
  },
  methods: {
    reorder(oldIndex, newIndex) {
      // move the item in the underlying array
      this.list.splice(newIndex, 0, this.list.splice(oldIndex, 1)[0]);
      // update order properties based on position in array
      this.list.forEach(function(item, index){
        item.order = index;
      });
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

您可以reorder()根据需要优化方法。

这是jsfiddle更新版本

我觉得这是一种功能,应该尝试将其打包到一个自定义指令中,但是我还没有弄清楚该怎么做。