【问题标题】:vuejs2 draggable and sortable listvuejs2 可拖动和可排序列表
【发布时间】:2018-04-06 10:16:35
【问题描述】:

我有一个可通过拖放进行排序的列表。它有效 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;
      }
    }
  }
});

【问题讨论】:

    标签: drag-and-drop vuejs2 jquery-ui-sortable


    【解决方案1】:

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

    sortedData() 是您的 codepen 中的一个计算元素,这意味着它将在其依赖项更新时执行(在您的情况下,changeOrder() 在拖放操作上执行)。

    改用一个方法,这样它只会在您的选择被以下更改事件更新时执行:

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

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

    Documentation about computed vs methods.

    【讨论】:

    • 好的,所以“sortedData”没有返回任何数据,它只是操纵数据对象......所以我可以删除方法中的返回。更新了你的代码笔 codepen.io/destroy90210/pen/jGgNBN
    • 是的,Vue 将根据这些数据操作更新 DOM。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 2012-06-23
    相关资源
    最近更新 更多