Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js swap array items

In my vue.js application I'm trying to swap 2 forum rows like this:

export default {
        data() {
            return {
                forums: []
            }
        },

        methods: {
            increment(forum, index) {
                ForumService.increment(forum)
                    .then(() => {
                        let b = this.forums[index];
                        this.forums[index] = this.forums[index++];
                        this.forums[index++] = b;
                    });
            }
        }
    }

But nothing happens? What am I doing wrong here?

like image 482
Jenssen Avatar asked Jan 25 '17 16:01

Jenssen


1 Answers

While @dfsq is correct about the use of index++ Vue doesn't recognize native mutations of arrays due to the inability to observe them. you have to use a mutation method to change them.

try this:

.then(() => {
  let rows = [this.forums[index], this.forums[index + 1]];
  this.forums.splice(index, 2, rows[1], rows[0] );
});

I haven't tested it and I'll edit when I can.

like image 75
Justin MacArthur Avatar answered Nov 13 '22 11:11

Justin MacArthur