1.定义
1.一种组件间通信的方式,适用于: 子组件===>父组件
2.使用场景:A是父组件,B是子组件,B想给A传递数据,那么就给在A中给B绑定自定义事件(事件的回调在A中)
3.绑定自定义事件:
1.方式一
在父组件中:
<School @getSchoolName="getSchoolName" />
或者
<School v-on:getSchoolName="getSchoolName" />
2.方式二 在父组件中定义ref
<School ref="schoolName"/>
mounted(){
this.$refs.XXXX.$on('getSchoolName',this.getSchoolName)
},
methods:{
getSchoolName(name){
this.schoolName = name
}
}
3.若想让自定义事件只能触发一次,可以使用once修饰符或者$once方法
4.触发自定义事件:在子组件中定义函数
this.$emit('getSchoolName',this.schoolName)
5.解绑自定义事件
this.$off('getSchoolName')
6.组件上绑定原生DOM事件,需要使用native修饰符
7.通过ref绑定自定义事件,回调要么配置在methods中,要么使用箭头函数,否则this的指向会出问题
8.使用ref绑定自定义事件相比于@和v-on的好处:ref可以更加灵活,比如添加setInterval函数,可以给事件绑定设置延迟
2.示例
需求:点击按钮,将子组件scholl和student的schoolName和studentName传给父组件App
在school组件中:
<div class="school">
<span>{{schoolName}}</span>
<button @click="sendShoolName">将学校名传给父组件</button>
</div>
export default {
data(){
return{
schoolName:'北京大学'
}
},
methods:{
sendShoolName(){
this.$emit('getSchoolName',this.schoolName)
}
}
}
在student组件中:
<div class="student">
<span>{{studentName}}</span>
<button @click="sendStudentName">将学生名传给父组件</button>
</div>
export default {
data(){
return{
studentName:'张三'
}
},
methods:{
sendStudentName(){
this.$emit('getStudentName',this.studentName)
}
}
}
在父组件App中
<div id="app">
<!-- 使用@或者v-on自定义事件 -->
<!-- <School @getSchoolName="getSchoolName" /> -->
<!-- 使用ref自定义事件 -->
<School ref="schoolName"/>
<!-- 在组件中使用原生的click事件需要加上native修饰符 -->
<Student @getStudentName="getStudentName" @click.native="show"/>
<span>{{studentName}}</span>
<span>{{schoolName}}</span>
</div>
import School from './components/school.vue'
import Student from './components/student.vue'
export default ({
name:'App',
components:{School,Student},
data(){
return{
studentName:'',
schoolName:''
}
},
mounted(){
setInterval(()=>{
this.$refs.schoolName.$on('getSchoolName',this.getSchoolName)
},3000)
},
methods:{
show(){
alert('哈哈哈')
},
getSchoolName(name){
console.log('###',name);
this.schoolName = name
},
getStudentName(name){
console.log('###',name);
this.studentName = name
}
}
})