将数据从子输入元素传递到父输入元素



我想将数据从子comp的input元素传输到父comp data属性
使用$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>


你必须指定一个发射选项在子组件中文档

在你的例子中应该是这样的

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

最新更新