子组件传值父组件$emit
子组件
let child=Vue.extend({
template: '#child',
methods: {
btnClick() {
this.$emit("parentreceive","param")
}
}
})
父组件
let parent=Vue.extend({
template: '#parent',
components:{
child
},
methods: {
receive(data){
console.log(data)
}
}
})
<template id="parent">
<div style="height: 500px;width: 600px;
background-color: skyblue;border: 5px solid black;">
<child @parentreceive="receive"></child>
</div>
</template>
<template id="child">
<div style="height: 200px;width: 400px;
background-color: palevioletred;border: 5px solid black;">
<button @click="btnClick">通过函数传值父组件</button>
</div>
</template>
<div id="app">
<parent></parent>
</div>
在子组件为button添加一个点击事件btnClick:
btnClick() {
this.$emit("parentreceive","param")
}
1、在使用的子组件标签中进行处理
1、使用$emit向在父组件使用的child标签传递一个函数,param是此函数的参数
2、在child标签中接收函数
<template id="parent">
<div style="height: 500px;width: 600px;
background-color: skyblue;border: 5px solid black;">
<child @parentreceive="receive"></child>
</div>
</template>
receive是一个函数,需要在父组件中定义:
methods: {
receive(data){
console.log(data)
}
}
这样就接收到传来的参数param
2、使用$on绑定
不同之处在父组件处理中:
<template id="parent">
<div style="height: 500px;width: 600px;
background-color: skyblue;border: 5px solid black;">
<child ref="child" ></child>
</div>
</template>
let parent=Vue.extend({
template: '#parent',
components:{
child
},
mounted() {
this.$refs.child.$on("parentreceive",(data)=>{
console.log(data)
})
},
beforeDestroy() {
this.$refs.child.$off("receive")
}
})
使用this.$refs等到指定的子标签(子组件实例)
$on 绑定事件
$off 解绑事件
本文介绍了Vue.js中父子组件间通信的方法,重点讲解了如何使用$emit触发父组件方法并传递参数,以及通过$on在父组件中监听子组件事件。示例代码详细展示了子组件如何调用btnClick方法触发parentreceive事件,并在父组件中定义receive方法接收并打印传入的参数。同时,还提到了使用$refs和$on的另一种通信方式,以及在组件销毁前使用$off解除事件绑定,确保资源释放。
5525

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



