繁体   English   中英

将数据从子输入元素传递给vue中的父元素

[英]pass data from child input element to parent in vue

我想将数据从子组件的输入元素传输到父组件数据属性
使用$emit方法可以将数据传输给父级
使用v-bind <input v-model="userinput" />直接将传输的属性绑定到子属性上会导致警告

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>

进行这种操作的正确方法是什么?

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





您必须在子组件文档中指定一个 emits选项

所以在你的情况下应该是这样的

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM