v-for和自定义组件的未定义行为 [英] Undefined Behavior with v-for and custom components

查看:94
本文介绍了v-for和自定义组件的未定义行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,请原谅糟糕的代码(我们现在没有时间修复)。我知道 eval 很可怕,但就我们的目的而言,这是唯一对我们如此容易的事情。

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

要重新创建问题,请添加一行。然后,更改新行上的文本。尝试删除倒数第二行-请注意,它不会被删除,但最后一行是被删除的。但是,如果您查看json-debug(它是后端数据的实时视图),则会看到正确的行被删除了!

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!

为什么会这样?为什么UI和后端不同步?

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

推荐答案

您应始终使用 v-for 进行迭代时,vuejs.org/v2/guide/list.html#key rel = nofollow noreferrer>键。尝试添加这样的内容。

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">

这篇关于v-for和自定义组件的未定义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆