当前位置:   article > 正文

Vue组件的自定义事件_this.$refs.mf.$on(

this.$refs.mf.$on(

用于子组==>父组件通信。理解:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件

1.第一种方式在父组件中:

  1. <Demo @atguigu="test"/><Demo v-on:atguigu="test"/>
  2. @ === v-on:

第二种方式在父组件中:1.使用ref在父组件给子组件打上标签

  1. <Demo ref='demo'>
  2. .....
  3. methods: {
  4. test(data){
  5. consolo.log('父组件收到的数据',data)
  6. }
  7. },
  8. monted(){
  9. //this.$ref.demo.$on('test',自定义事件的回调)
  10. this.$ref.demo.$on('test',this.test)
  11. }

 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. 1.
  2. methods:{
  3. test(){
  4. consolo.log('回调')
  5. }
  6. }
  7. mounted(){
  8. this.$refs.demo.$on('test',this.test)
  9. }
  10. 2.使用箭头函数
  11. mounted(){
  12. this.$refs.demo.$on('test',()=>{
  13. consolo.log(this) //指向当前组件
  14. })
  15. }
  16. 3.this错误指向
  17. mounted(){
  18. this.$refs.demo.$on('test',function(){
  19. consolo.log(this) //指向调用test的组件
  20. })
  21. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/411183
推荐阅读
相关标签
  

闽ICP备14008679号