vuejs2 可拖拽排序列表

vuejs2 draggable and sortable list

我有一个可以通过拖放进行排序的列表。它有效 https://codepen.io/destroy90210/pen/rGEodB

现在我想包含按名称、日期和位置对列表进行排序的功能。

因此,如果我看到按名称或日期排序的列表,我会阻止拖放功能。只有选择位置,从下拉列表中,这些项目是可拖动的,但是现在我的拖放不再起作用。项目跳回到原来的位置...

https://codepen.io/destroy90210/pen/yzdQxK

<div id="main">
  <select class="dd" v-model="orderBy" @change="sortedData">
    <option value='created'>created</option>
    <option value='abc'>Abc</option>
    <option value='position'>Position</option>
  </select>
  <draggable :list="data" class="dragArea" @change="changeOrder" :options="{draggable:'.card--dragable'}">
    <div :class="{'card--dragable': isDragable}" class="card" v-for="item in sortedData"><span class="card__label">{{item.name}}</span></div>
  </draggable>
</div>

new Vue({
  el: "#main",
  data: {
    data: data,
    orderBy: 'position',
    isDragable: true,
  },
  computed:{
    sortedData(){
      this.isDragable = false;
      if (this.orderBy === 'abc') {
        return this.data.sort((a, b) => { return a.name.localeCompare(b.name); });
      } else if (this.orderBy === 'created') {
        return this.data.sort((a, b) => { return a.id > b.id; });
      }
      this.isDragable = true;
      return this.data.sort((a, b) => { return a.position > b.position; });
      },
    },
    methods:{
      changeOrder(e){
      const oldIndex = e.moved.oldIndex;
      const newIndex = e.moved.newIndex;

      let i = Math.min(oldIndex, newIndex);
      const max = Math.max(oldIndex, newIndex) + 1;
      for (i; i < max; i += 1) {
        this.data[i].position = i;
      }
    }
  }
});

修复:https://codepen.io/destroy90210/pen/jGgNBN

sortedData() 是代码笔中的计算元素,这意味着它将在其依赖项更新时执行(在您的情况下,当 changeOrder() 在 drag/drop 操作上执行时)。

改用一种方法,以便它仅在您的 select 被以下更改事件更新时执行:

<select class="dd" v-model="orderBy" @change="sortedData">

这意味着我们可以通过将 sortedData() 从计算移动到方法来解决问题。 现在它不会再更新了。

Documentation about computed vs methods.