How to bind a sortable list to vuejs?

Asked By: Anonymous

I am trying to bind a sortable list in Vue.js, but the underlying data list is not updated:

_x000D_

_x000D_

Vue.component('lessons', {_x000D_
  template: "#lessons-template",_x000D_
_x000D_
  data: function() {_x000D_
    return {_x000D_
      list: ['Item 1', 'Item 2', 'Item 3']_x000D_
    };_x000D_
  },_x000D_
_x000D_
  methods: {_x000D_
    onChange: function(evt) {_x000D_
      console.log(this.list); // allways ['Item 1', 'Item 2', 'Item 3']_x000D_
    }_x000D_
  },_x000D_
_x000D_
  ready: function(value) {_x000D_
    Sortable.create(this.$els.sortable, {_x000D_
      draggable: 'li',_x000D_
      onSort: this.onChange_x000D_
    });_x000D_
  }_x000D_
});_x000D_
_x000D_
new Vue({ el: 'body'});

_x000D_

ul { list-style: none;}_x000D_
ul li { padding: 10px; display: block; background: #EFEFEF; margin-bottom: 5px;}

_x000D_

https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js_x000D_
http://rubaxa.github.io/Sortable/Sortable.js_x000D_
_x000D_
  <div>_x000D_
    <lessons></lessons>_x000D_
  </div>_x000D_
_x000D_
  <template id="lessons-template">_x000D_
_x000D_
    <ul v-el:sortable>_x000D_
      <li v-for="item in list">{{ item }}</li>_x000D_
    </ul>_x000D_
    _x000D_
    <pre>{{ list | json }}</pre>_x000D_
  </template>

_x000D_

_x000D_

x000D


Solution

Answered By: Anonymous

Here we go:

Vue.js:

Vue.component('lessons', {
  template: "#lessons-template",

  data: function() {
    return {
      list: ['Item 1', 'Item 2', 'Item 3']
    };
  },

  methods: {
    onChange: function(evt) {
      console.log(this.list); // allways ['Item 1', 'Item 2', 'Item 3']
    }
  },

  ready: function(value) {
    var self = this;
    Sortable.create(this.$els.sortable, {
      draggable: 'li',
      onSort: this.onChange,
      onEnd: function (evt) {
        self.list.splice(evt.oldIndex,1);
        self.list.splice(evt.newIndex,0,evt.item.id);       
    },
    });
  }
});

new Vue({ el: 'body'});

HTML:

<div>
    <lessons></lessons>
</div>

<template id="lessons-template">
   <ul v-el:sortable>
     <li v-for="item in list" id="{{item}}">{{ item }}</li>
    </ul>
</template>

Working Vue.js Sortable jsFiddle: https://jsfiddle.net/crabbly/vhsd3wwu/

techinplanet staff

techinplanet staff


Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno