一、通过父组件给子组件传递函数类型的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');
}
注意:
  1. 若想让自定义事件只能触发一次,可以使用once修饰符,或者$once方法。

  2. 组件上也可以绑定原生DOM事件,需要使用native修饰符

    <Child @click.native="xxx"></Child>
    
  3. 通过this.$refs.xxx.$on('haha', 回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this的指向会出问题。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐