1

我正在使用 Sortable.js 和 Vue.js。目标是对项目进行排序并保持数据更新。

它在 Vue 1.x 中运行良好,但在更新到 2.0 后排序变得不正确。数组仍然正确更新,但 DOM 中的项目位于错误的位置。

new Vue({
  el: '#app',
  template: '#sort',
  data: function() {
    return {
      items: [
        "http://placehold.it/200X300?text=image1",
        "http://placehold.it/200X300?text=image2",
        "http://placehold.it/200X300?text=image3",
        "http://placehold.it/200X300?text=image4"
      ],  
    }
  },
  mounted: function() {
    this.$nextTick(function () {
      Sortable.create(document.getElementById('sortable'), {
        animation: 200,
        onUpdate: this.reorder.bind(this),
      });
    })
  },
  methods: {
    reorder: function(event) {
        var oldIndex = event.oldIndex,
            newIndex = event.newIndex;
        this.items.splice(newIndex, 0, this.items.splice(oldIndex, 1)[0]);

    } 
   }
});

jsFiddle https://jsfiddle.net/4bvtofdd/4/

有人能帮我吗?

4

3 回答 3

5

我今天遇到了类似的问题。

添加 :key 值以确保在 Sortable 更改项目顺序后 Vue 以正确的顺序重新呈现元素

<div v-for="item in items" :key="item.id">
  <!-- content -->
</div>

https://vuejs.org/v2/guide/list.html#key

于 2017-03-14T19:37:43.647 回答
4

碰巧的是,Sortable 会跟踪 in 中的顺序sortable.toArray(),因此很容易进行计算,以按排序顺序为您提供项目,而原始项目列表保持不变。

new Vue({
  el: '#app',
  template: '#sort',
  data: {
    items: [
      "http://placehold.it/200X300?text=image1",
      "http://placehold.it/200X300?text=image2",
      "http://placehold.it/200X300?text=image3",
      "http://placehold.it/200X300?text=image4"
    ],
    order: null
  },
  computed: {
    sortedItems: function() {
      if (!this.order) {
      	return this.items;
      }
      return this.order.map((i) => this.items[i]);
    }
  },
  mounted: function() {
    this.$nextTick(() => {
      const sortable = Sortable.create(document.getElementById('sortable'), {
        animation: 200,
        onUpdate: () => { this.order = sortable.toArray(); }
      });
    })
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/Sortable/1.4.2/Sortable.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="//unpkg.com/vue@2.0.1/dist/vue.js"></script>
<div id='app'></div>
<template id="sort">
  <div class="container">
    <div class="row sort-wrap" id="sortable">
      <div class="col-xs-6 col-md-3 thumbnail" v-for="(item, index) in items" :data-id="index">
        <img v-bind:src="item" alt="" class="img-responsive">
      </div>
    </div>
    <div v-for="item in sortedItems">
    {{item}}
    </div>
  </div>
</template>

于 2016-10-05T16:42:39.200 回答
0

确保您没有使用道具,否则您将无法排序。如果您正在使用道具,请将道具数据分配给数据属性并改用数据属性。

于 2017-04-24T12:04:08.660 回答