用于子组==>父组件通信。理解:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件
1.第一种方式在父组件中:
<Demo @atguigu="test"/> 或 <Demo v-on:atguigu="test"/>
@ === v-on:
第二种方式在父组件中:1.使用ref在父组件给子组件打上标签
<Demo ref='demo'>
.....
methods: {
test(data){
consolo.log('父组件收到的数据',data)
}
},
monted(){
//this.$ref.demo.$on('test',自定义事件的回调)
this.$ref.demo.$on('test',this.test)
}
2.在子组件中触发自定义事件
this.$emit('test',this.data)
解绑事件(一般在组件销毁的时候,将组件解绑)
this.$off('test')
3.也可以绑定原生的DOM事件使用.native
<Demo ref="demo" @click.native="show"/>
特别注意,通过this.$refs.xxx.$on('test',回调)
绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!未使用箭头函数的函数形式
1.
methods:{
test(){
consolo.log('回调')
}
}
mounted(){
this.$refs.demo.$on('test',this.test)
}
2.使用箭头函数
mounted(){
this.$refs.demo.$on('test',()=>{
consolo.log(this) //指向当前组件
})
}
3.this错误指向
mounted(){
this.$refs.demo.$on('test',function(){
consolo.log(this) //指向调用test的组件
})
}