首页 > 解决方案 > 如何将输入数据值从子组件数据对象发送到父组件?

问题描述

我正在尝试通过数据对象'data()'将输入数据变量从子组件表单发送到父组件。我已经看到vuejs 从子组件文章中更新父数据并尝试这样做,但是我无法通过事件 $emit 捕获的数据对象。你能帮帮我吗?

父组件:

<script>
    import inputform from '../components/form.vue';
    import axios from 'axios';

  export default {
      name: 'helloword',
      data() {
          return {
          }
      },
    components: {
        inputform
    },
      methods: {
          submit() {
                const path = 'http://127.0.0.1:5000';
                axios.post(path, {
                    name: inputform.data()

                })
              .then(() => {
                  const result = 'Sucess!';
                  console.log(result);
              })
              .catch((error) => {
                  console.log(error);
              })
          }
      }
  }
</script>

子组件:

<template>
    <div>
  <table>
    <thead>
    <th>Name</th>
    <th>Email</th>
    <th>Age</th>
    </thead>
    <tr>
      <td><input type="text" id="name" v-model="details.name" @focusout="inputdata"></td>
      <td><input type="text" id="name1" v-model="details.name1" @focusout="inputdata" ></td>
      <td><input type="number" id="age" v-model="details.age" @focusout="inputdata" ></td>

    </tr>
  </table>
    </div>
</template>

<script>
    export default {
        name: "inputform",
      data() {
          return {
            details: {
            name: '',
            name1: '',
            age: ''
              }
          }
      },
      methods: {
            inputdata() {
              this.$emit("input_data", this.details)
            }
      }
    }
</script>

<style scoped>

</style>

因此,寻求帮助将变量数据从子组件发送到父组件,并使用父组件的 axios 向 API 执行提交操作。如果还有其他更好的方法请告诉我。谢谢。

标签: vue.jsvue-component

解决方案


首先,您应该将最多两个参数传递给 $emit 方法,这是文档:https ://vuejs.org/v2/api/#vm-emit ,第二个是v-on:之前的 v-models 是额外的。所以解决方案你可以在一个对象中传递这个数据而不是三个数据,所以代码将是这样的:


      data() {
          return {
            name: '',
            email: '',
            age: '',
          }
      },
      methods: {
            inputdata() {
              this.$emit("input", {
                name: this.name, 
                email: this.email, 
                age: this.age
              })
            }
      }

或者我更喜欢的选项将所有内容放在这样的表单数据中

<template>
    <div>
  <table>
    <thead>
    <th>Name</th>
    <th>Email</th>
    <th>Age</th>
    </thead>
    <tr>
      <td><input type="text" id="name" v-model="form.name"></td>
      <td><input type="email" id="email" v-model="form.email"></td>
      <td><input type="number" id="age" v-model="form.age"></td>
    </tr>
  </table>
    </div>
</template>

<script>
    export default {
        name: "inputform",
      data() {
          return {
            form: {
              name: '',
              email: '',
              age: '',
            }
          }
      },
      methods: {
            inputdata() {
              this.$emit("input", this.form)
            }
      }
    }
</script>

推荐阅读