Steef0w
Steef0w

Reputation: 53

Undefined Behavior with v-for and custom components

First off, please excuse the awful code (we don't have time to fix right now). I know eval is horrible, but for our purposes it was the only thing that worked for us this easily.

This is how we add and remove the rows:

methods: {
    addRow: function() {
        let lastRow = eval(`this.$parent.json${this.path}[this.$parent.json${this.path}.length - 1]`);
        lastRow = Object.assign({}, lastRow);
        eval(`this.$parent.json${this.path}.push(lastRow)`);
        this.$forceUpdate();
    },
    removeRow: function(index) {
        //eval(`this.$parent.json${this.path}.splice(index, 1)`);
        eval(`Vue.delete(this.$parent.json${this.path}, index)`);
        this.$forceUpdate();
    }

https://jsfiddle.net/00e58as4/10/6

To recreate the issue, add a row. Then, change the text on the new row. Try removing the second-to-last row - notice how it doesn't get deleted, but the last one is. However, if you check the json-debug which is a live view of the backend data, you'll see that the proper row gets deleted!

Why does this happen? Why are the UI and the backend not in sync?

Upvotes: 1

Views: 353

Answers (1)

Bert
Bert

Reputation: 82489

You should always use a key when iterating with v-for. Try adding one like this.

<div class = "well" v-for = "item, index in items" :key="item">

Upvotes: 4

Related Questions