javascript - 带有父子的Vue表单转发器
问题描述
我对 Vue 表单转发器有一些问题。我正在尝试制作本身具有中继器的中继器,我用父母和孩子做了一个例子。问题是与孩子的推送方法,但我不知道如何解决它。
这是代码示例:CODEPEN
<template>
<div id="app">
<div v-for="(parent, index) in form.parent" class="form-repeater">
<div class="form">
<p>Insert Parent</p>
<input v-model="name" placeholder="Name">
<input v-model="age" placeholder="age">
<hr>
<p>Children</p>
<div v-for="(child, index) in form.parent.children" class="form-repeater">
<input v-model="name" placeholder="Name">
<input v-model="school" placeholder="school">
</div>
<button @click="addChild">Add children</button>
</div>
</div>
<button @click="addParent">Add parent</button>
</div>
</template>
<script>
export default {
data() {
return {
form: {
parent: [{
child: []
}],
},
};
},
methods: {
addParent: function () {
this.form.parent.push({
name: '',
age: '',
});
},
addChildren: function (index) {
this.form.parent[index].children.push({
child: {
name: '',
school: '',
}
});
},
}
};
</script>
所以你可以在codepen上看到,我可以添加父母,但孩子没有按预期工作,我在这里做错了什么?
解决方案
试试这个。
methods: {
addParent: function () {
this.form.parent.push({
name: '',
age: '',
children: []
});
},
addChildren: function (indexp) {
console.log(indexp);
this.form.parent[indexp].children.push({
child: {
name: '',
school: '',
}
});
console.log(this.form.parent)
},
}
我对您的代码进行了一些更改:
- 向父对象添加了类型为数组的子属性
- 更改了 addChildren 函数。现在子元素被推入传递给 addChildren 函数的索引父元素的子数组中
推荐阅读
- java - MacOS 上的 STS 错误:找不到主类(我已经尝试了所有能找到的解决方案)
- scala - 使用 scala 合成糖来收集 case 和 if
- string - 在 C++ 中对列表框进行排序
- nginx - HAproxy 健康检查底层应用
- zapier - 返回文件的 Zapier 触发器:z.dehydrateFile 调用的格式是什么?
- objective-c - React Native:获取本机模块大小
- ios - UISearchController 取消按钮不可点击
- r - 使用 R 中的 tm.package 对句子进行文本挖掘
- twitter-bootstrap - 为什么我们必须强制使用引导导航栏?
- java - Android:无法合并 dex - 多个 dex 文件定义 Lorg/apache/commons/lang3