Search code examples
javascriptvue.jsdata-bindingvue-componentvue-reactivity

pass data from child input element to parent in vue


I want to transmit the data from the input element of the child comp to the parent comp data property
using the$emit method the data can be transmited to the parent
directly binding the transmited property on the child property using v-bind <input v-model="userinput" /> results in a Warning

runtime-core.esm-bundler.js?5c40:6870 [Vue warn]: Extraneous non-emits event listeners (transmitData) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option. 
  at <UserInput onTransmitData=fn<bound receaveData> > 
  at <App>

what is the correct way to do this kind of operation ?

\\ child

<template>


     
     <input   v-model="userinput" /> 

    <button type="button" @click="transmitData">transmit</button>

</template>

<script>
export default {
 
        

data() {
    return {
        userinput: " dd",
      
    }
},

methods: {
    transmitData(event){
        this.$emit('transmit-data', this.userinput)
    }

}



}
</script>



\\ parent

<template>
 
  <user-input @transmit-data="receaveData" />



  <p>{{ childData }}</p>
</template>

<script>
import UserInput from "./components/UserInput.vue";

export default {
  name: "App",
  components: {
    UserInput,
  },

  data() {
    return {
    
      childData: " "
    };
  },

  methods: {

    receaveData(compTransmit){
      console.log(compTransmit)
      this.childData = compTransmit

    },

    
   
  },
};
</script>






Solution

  • you have to specify a emits option in the child component docs

    so in your case should look like this

    export default {
    emits: ['transmit-data'], // you need to add this :)
    data() {
        return { userinput: " dd" }
    },
    methods: {
        transmitData(event){
            this.$emit('transmit-data', this.userinput)
        }
    }
    }