一、场景描述
我们在页面开发中,难免要使用事件。
在之前的学习中,我们学过@click、@keyup、@change
等事件,这些是Vue
自带的事件。
它一般是用在原生的HTML元素上的。在组件上使用需要加native
修饰
比如:
h1绑定一个click事件:
<h1 @click="test">你好</h1>
input绑定一个keyup事件:
<input type="text" @keyup.enter="add"/>
在组件上绑定一个Vue原生事件:
<School @change.native="delete"/>
这一篇说的自定义事件,可以绑定到我们自己的Vue
组件上。
实现子组件给父组件传递数据的功能。
比如:
<School :getSchoolName="getSchoolName"/>
二、绑定自定义事件
方式1
使用@或v-on
方式绑定自定义事件
App
父组件中:
模板代码:
<Student @test="getStudentName"/>
methods
函数:
getStudentName(name,...params){console.log('App收到了学生名:',name,params)
}
Student
子组件中:
模板代码:
<button @click="sendStudentlName">把学生名给App</button>
methods
函数:
//触发Student组件实例身上的test事件 传递多个参数
this.$emit('test',this.name,666,888,900)
方式2
使用ref
方式绑定自定义事件
App
父组件中:
模板代码:
<Student ref="student"/>
mounted
属性:
mounted() {//设置三秒后再绑定事件// setTimeout(() => {// this.$refs.student.$on('test',this.getStudentName) //绑定自定义事件 第一个参数是事件名称,第二个参数是函数名称// },3000);// this.$refs.student.$on('test',this.getStudentName) //绑定自定义事件 第一个参数是事件名称,第二个参数是函数名称this.$refs.student.$once('test',this.getStudentName) //绑定自定义事件(一次性)}
Student
子组件中:
和方式1
相同
三、总结
原则:给那个组件的vc
实例绑定事件,就由那个组件的vc
实例来触发事件
相对来讲,第二种方法更灵活,第一种方法更简便,各有优势,视具体情况选择使用。