【问题标题】:VueJs getting child form data from parent componentVueJs 从父组件获取子表单数据
【发布时间】:2020-04-04 04:34:09
【问题描述】:

我的子组件中有一个表单:

<form @submit="submitForm">
  <input type="text" v-model="textInput" />
</form>

export default {
  name: "childComp",
  data: function() {
    return {
     textInput: ""
    }
  }
}

现在我的父组件中有一个按钮,我需要单击该按钮来获取子表单数据。

<button type="button" @click="getFormData()"> click </button>

export default {
  name: "ParentComp",
  data: function() {
    return {
     formData: []
    }
  },
  methods: {
    getFormData(d) {
      formData.push(d);
      console.log(d)
    }
  }
}

感谢您的帮助。

【问题讨论】:

标签: vue.js vuejs2 vue-component vuejs3


【解决方案1】:

即使您使用 $ref 解决了这个问题,我还是建议您在自定义组件中使用 v-model 实现的强大功能。

这是一种更简洁的方法,通过这样做,您将始终拥有表单数据,而不必在需要时实际检索它。

可以通过以下方式完成:

父母

<button type="button" @click="getFormData()"> click </button>
<childComp v-model="formData" />

export default {
  name: "ParentComp",
  data: function() {
    return {
     formData: {}
    }
  },
  methods: {
    getFormData() {
      console.log(this.formData)
    }
  }
}

孩子

<form>
  <input type="text" v-model="selected.text" />
</form>

export default {
  name: "childComp",
  props: ['value'],
  computed: {
    selected: {
      get() {
        return this.value;
      },
      set(value) {
        this.$emit('input', value);
      } 
    }
  }
}

【讨论】:

  • 如果表单中有 10 或 20 个字段,这是否合适?你会为表单中的每个元素创建一个计算对象,然后发出整个表单对象吗?
  • 老实说没问题,你不会遇到任何性能问题
【解决方案2】:

我使用ref="" 找到了解决方案。不知道将来会变得多复杂。

这就是我所做的。

My parent component:

<button type="button" @click="getFormData()"> click </button>
<childComp ref="childComp" />

export default {
  name: "ParentComp",
  data: function() {
    return {
     formData: []
    }
  },
  methods: {
    getFormData() {
      const data = this.$refs.childComp.submitForm()
      formData.push(data);
      console.log(data)
    }
  }
}

我的子组件:

<form @submit="submitForm">
  <input type="text" v-model="textInput" />
</form>

export default {
  name: "childComp",
  data: function() {
    return {
     textInput: ""
    }
  },
  submitForm() {
    return this.form;
  }
}

【讨论】:

    猜你喜欢
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 2017-04-09
    相关资源
    最近更新 更多