Vue如何在另一个中添加表单中继器



我对Vue形式的中继器有一些问题。

我想在另一个中建立一个形式的中继器。第一个按预期工作,但另一个(在第一个内部(由于某种原因不工作。

我认为问题是我没有用钥匙做什么,但我在这里寻求帮助,我尝试了一些方法,但它总是重复第一种形式,或者根本不起作用。

这是我的模板代码:

<!-- Start first repeater -->
<div v-for="(field, index) in form.first" v-bind:key="index" class="first-one" :style="{animation: 'fadeIn 0.5s'}">

<!-- I'm adding some inputs to have some differences, using bootstrap -->
<b-form-input color="success" v-model="field.first-repeater1" name="first" 
type="text" />
<b-form-input color="success" v-model="field.first-repeater2" name="second" />


<!-- And now I will start second repeater inside this one -->
<div v-for="(field2, iindex) in form.first.second" v-bind:key="iindex" class="sec-one" :style="{animation: 'fadeIn 0.5s'}">
<b-form-input color="success" v-model="field2.second_repeater_form1" name="second_repeater1" type="number" />
<b-form-input color="success" v-model="field2.second_repeater_form2" name="second_repeater2" />
</div> <!-- Closing second repeater -->
<b-button v-ripple.400="'rgba(113, 102, 240, 0.15)'" variant="outline-primary" pill @click="addSecondRepeater(index)">Button to add second repeater</b-button>
<div> <!-- Closing first repeater -->
<b-button v-ripple.400="'rgba(113, 102, 240, 0.15)'" variant="outline-primary" pill @click="addFirstRepeater">Button to add first repeater</b-button>

正如你们所看到的,我正在把第一个中继器的索引传给第二个中继器。因此,我有一个状态form.first,我需要在其中存储这些字段中的每一个信息,并在最后显示它应该是什么样子。

因此,让我们来看看一个脚本:

状态看起来是这样的:

form: {
first: [{
second: []
}],
},

// Adding fields for first repeater, and it works fine.

addFirstRepeater: function () {
this.form.first.push({
first-repeater1: '',
first-repeater2: '',
});
},

// Here is the error
addSecondRepeater: function (index) {
this.form.first[index].push({
second: {
second_repeater_form1: '',
second_repeater_form2: '',
}
});
},

因此,在这种情况下,对于函数addSecondRepeater,它将给出一个错误,如:

this.form.first[index].push不是函数

如果我删除[index],它将重复第一种形式。

这是代码笔上的示例https://codepen.io/rade-ilijev/pen/zYNvgqK有什么办法解决的吗?

显然,您正在推进一个对象,而不是一个数组。您的默认状态值是

form: {
first: [{
second: []
}],
},

您可以看到"first"中的元素不是数组,而是对象。当调用addFirstRepeater时,它正在数组中添加一个对象。所以在addSecondRepeater中,这个.form.first[index]指向的是一个对象而不是数组,push((函数可用于数组而不是对象。

如果你打算在你的主数组中只使用一个元素(我认为你这样做是因为我在代码中看到了它(,你可以将其添加到addSecondRepeater 中

this.form.first[0][index].push()

而不是

this.form.first[index].push()

其中"index"是数组"first"第0个索引处对象中键值对的键

最新更新