一、通过父组件给子组件传递函数类型的props实现
父组件:
<Child :getChildInfo="getChildInfo"></Child>
子组件:
<button @click="sendChildInfo"></button>
props: ['getChildInfo']
sendChildInfo() {
this.getChildInfo(数据);
}
二、通过父组件给子组件绑定自定义事件实现
第一种方式:
父组件:
<child @haha="test"></child>
子组件:
<button @click="send"></button>
send() {
this.$emit('haha');
}
第二种方式:
父组件:
<child ref="xxx"></child>
mounted() {
this.$refs.xxx.$on('haha', this.test);
}
子组件:
<button @click="send"></button>
send() {
this.$emit('haha');
}
注意:
-
若想让自定义事件只能触发一次,可以使用
once修饰符,或者$once方法。 -
组件上也可以绑定原生DOM事件,需要使用
native修饰符<Child @click.native="xxx"></Child> -
通过
this.$refs.xxx.$on('haha', 回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this的指向会出问题。
博客介绍了Vue中父子组件通信的实现方式。一是通过父组件给子组件传递函数类型的props实现;二是通过父组件给子组件绑定自定义事件实现,还给出两种绑定自定义事件的方式。同时提醒了使用自定义事件的注意事项,如触发次数、this指向等。
3292

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



