这是子组件的
<template>
<div class="app">
<input @click="sendMsg" type="button" value="给父组件传递值">
</div>
</template>
export default {
data () {
return {
//将msg传递给父组件
msg: "我是子组件的msg",
}
},
methods:{
sendMsg(){
//func: 是父组件指定的传数据绑定的函数,this.msg:子组件给父组件传递的数据
this.$emit('bec',this.msg)
}
}
}
这是父组件的
<template>
<div class="app">
<child @bec="getMsgFormSon"></child>
</div>
</template>
import child from './child.vue'
export default {
data () {
return {
msgFormSon: "this is msg"
}
},
components:{
child,
},
methods:{
getMsgFormSon(data){
this.msgFormSon = data;
console.log(this.msgFormSon)
}
}
}
在子组件中sendMsg函数中 this.$emit('bec',this.msg) 获取msg参数后在点击过程中发生
<child @bec="getMsgFormSon"></child>
在父级里函数获取 this.msgFormSon = data; ,参数传递上来后 msgFormSon 参数发生变化,则传递成功
本文介绍了一个Vue.js项目中,如何实现子组件向父组件传递数据的过程。通过子组件中的sendMsg函数,使用this.$emit触发事件,将数据传递给父组件。父组件通过监听@bec事件,调用getMsgFormSon方法接收并处理子组件传递的数据。

被折叠的 条评论
为什么被折叠?



