繁体   English   中英

带有 Vue 2.0 的 Sortable.js 排序不正确

[英]Sortable.js with Vue 2.0 sorts incorrectly

我正在使用 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/

有人能帮我吗?

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

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

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

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

碰巧,Sortable 会跟踪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>

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM