[Vuejs]-How to send input data value from child component data object to parent?

0👍

When attaching a v-model you don’t need a v-on. You could also look to capture details into a single object like so and then pass it as part of the event emitted.

Child component

<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">
        </td>
        <td>
          <input type="email" id="email" v-model="details.email">
        </td>
        <td>
          <input type="number" id="age" v-model="details.age">
        </td>
        <td>
          <button @click="inputdata">Submit</button>
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  name: "inputform",
  data() {
    return {
      details: {
        name: "",
        email: "",
        age: ""
      }
    };
  },
  methods: {
    inputdata() {
      console.log(this.details);
      this.$emit("handledata", this.details);
    }
  }
};
</script>

Parent component

<template>
  <div id="app">
    <HelloWorld v-on:handledata="handleInput"/>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld
  },
  methods: {
    handleInput(data) {
      // object emitted from the child component
      console.log({ data });
    }
  }
};
</script>

0👍

well first you should pass max two params to $emit method here’s the docs: https://v2.vuejs.org/v2/api/#vm-emit and second is the v-on: before v-models is extra.
so the solution you can pass this data in one object instead of three data so the code will be like this:


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

or my prefer option put all in a form data like this

<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>

Leave a comment