首页 > 解决方案 > 带有父子的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上看到,我可以添加父母,但孩子没有按预期工作,我在这里做错了什么?

标签: javascriptvue.jsvuejs2

解决方案


试试这个

    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 函数的索引父元素的子数组中

推荐阅读