组件的自定义事件
- 
一种组件间通信的方式,适用于:子组件 ===> 父组件
 - 
使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。
 - 
绑定自定义事件:
- 
第一种方式,在父组件中:
<Demo @atguigu="test"/>或<Demo v-on:atguigu="test"/> - 
第二种方式,在父组件中:
<Demo ref="demo"/> ...... mounted(){ this.$refs.xxx.$on('atguigu',this.test) } - 
若想让自定义事件只能触发一次,可以使用
once修饰符,或$once方法。this.$refs.student.$on('atguigu',this.getStudentName) //绑定自定义事件 // this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件(一次性) 
 - 
 - 
触发自定义事件:
this.$emit('atguigu',数据) - 
解绑自定义事件
this.$off('atguigu') - 
组件上也可以绑定原生DOM事件,需要使用
native修饰符。<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) --> ...... <Student ref="student" @click.native="show"/> - 
注意:通过
this.$refs.xxx.$on('atguigu',回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题! 
                    
                
                
            
        
浙公网安备 33010602011771号