Vue:自定义事件

组件自定义事件

组件自定义事件完成的功能:子组件给父组件传数据。是的,就这么简单;

自定义事件三步走

想要实现组件自定义事件,流程只需三步:

  1. 在父组件中给子组件绑定 自定义事件
  2. 子组件中触发事件
  3. 父组件调用触发事件后的业务逻辑

代码实现

给子组件绑定自定义事件

静态绑定

<template>
	<div class="app">
		<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
		<School :getSchoolName="getSchoolName"/>
	</div>
</template>

自定义事件名为:getSchoolName

动态绑定

<Student ref="student"/>

this.$refs.student.$on('getSchoolName',this.getSchoolName)

子组件触发事件

		methods: {
			sendStudentlName(){
				this.$emit('getSchoolName')
			}
		}

父组件调用触发事件后的业务逻辑

		methods: {
			getSchoolName(){
				console.log('App收到了学校名:')
			}
		}

解绑

有自定义事件绑定,那自然也有解绑。解绑由子组件来触发,父组件不需要做什么事,如下:

this.$off('atguigu') //解绑一个自定义事件
this.$off(['atguigu','demo']) //解绑多个自定义事件
this.$off() //解绑所有的自定义事件

解绑后的事件,子组件再进行触发就不好使了。

posted @ 2022-07-25 13:34  爱编程DE文兄  阅读(134)  评论(0编辑  收藏  举报