Aaroniker Aaroniker - 10 days ago 7
Javascript Question

Re-render DOM if index of data elements changed

Vue.js doesnt detect that i swap 2 array elements in my data object:

data: {
list: [
'Foo',
'Bar',
'Test'
]
}


Method to swap entries:

swapIndex: function(from, to) {

var first = this.list[from];
this.list[from] = this.list[to];
this.list[to] = first;

}


JsFiddle https://jsfiddle.net/aaroniker/r11hxce8/

I want re-render the
v-for
loop if i swap the indexies.

Thanks!

Answer

here is the solution I came with. I created a copy of your list to modify it, and I invoked the this.$set() method on the list:

new Vue({
    el: '#app',
    data: {
        list: [
            'Foo',
            'Bar',
            'Test'
        ]
    },
    methods: {
        swapIndex: function(from, to) {
            var copy = JSON.parse(JSON.stringify(this.list))
            var first = copy[from];
            copy[from] = copy[to];
            copy[to] = first;
            this.$set(this,'list',copy)
            console.log(this.list);

        }
    }
})
Comments