Updating array order in Vue.js after changing DOM

I have a Vue.js main object:

var playlist = new Vue({
    el : '#playlist',
    data : {
        entries : [
            { title : 'Oh No' },
            { title : 'Let it Out' },
            { title : 'That\ Right' },
            { title : 'Jump on Stage' },
            { title : 'This is the Remix' }
        ]
    }
});

HTML:

<div id="playlist">
    <div v-for="entry in entries">
        {{ entry.title }}
    </div>
</div>

I also use the dragula library to allow users to rearrange the #playlist div.

However, after the user reorders the playlist using dragula, this change is not reflected in Vue playlist.entries, only in the DOM.

I hooked into dragula events to determine the start index and end index of the moved item. What is the correct way to update a Vue object to reflect the new order?

Fiddle: https://jsfiddle.net/cxx77kco/5/

+4
source share
4 answers

Vue v-for DOM. , , dragula . : https://jsfiddle.net/hsnvweov/

var playlist = new Vue({
    el : '#playlist',
    data : {
        entries : [
            { title : 'Oh No' },
            { title : 'Let it Out' },
            { title : 'That\ Right' },
            { title : 'Jump on Stage' },
            { title : 'This is the Remix' }
        ]
    },
    ready: function() {
        var self = this;
        var from = null;
        var drake = dragula([document.querySelector('#playlist')]);

        drake.on('drag', function(element, source) {
            var index = [].indexOf.call(element.parentNode.children, element);
            console.log('drag from', index, element, source);
            from = index;
        })

        drake.on('drop', function(element, target, source, sibling) {
            var index = [].indexOf.call(element.parentNode.children, element)
            console.log('drop to', index, element, target, source, sibling);

            self.entries.splice(index, 0, self.entries.splice(from, 1)[0]);

            console.log('Vue thinks order is:', playlist.entries.map(e => e.title ).join(', ')
            );
        })
    }
});
+6

Vue, .

, v-for drag-and-drop viewmodel:

example

Syntaxe:

<div v-dragable-for="element in list">{{element.name}}</div>

: 1, 2

Github: Vue.Dragable.For

+2

$remove $set?

Vue.js

0

Source: https://habr.com/ru/post/1627513/


All Articles