关于组件通讯一些自己理解

关于组件通信你必须要理解一件事:事件派发者与监听者是同一个。也就是说谁派发的就由谁监听。

一,事件总线

任意两个组件之间传值常⽤事件总线 或 vuex的⽅式。

1,局部事件总线

main.js:

export var $burVue = new Vue()  

childA:

import {$burVue} from '../main'

$parent.$emit('changeFather', 'A')

childB:

import {$burVue} from '../main'

$burVue.$on('changeFather', (data) => {

 this.title = data

})

2,全局事件总线

main.js:

Vue.prototype.$burVue = new Vue()

childA:

this.$burVue.$emit('changeFather', 'A')

childB:

this.$burVue.$on('changeFather', (data) => {

 this.title = data

})

3,采用发布,订阅原理的全局事件总线

main.js:

var EventBus = new Vue();

Object.defineProperties(Vue.prototype, {

  $burVue: {

    get: function () {

      return EventBus

    }

  }

})

childA:

this.$burVue.$emit('changeFather', 'A')

childB:

this.$burVue.$on('changeFather', (data) => {

 this.title = data

})

4,注意事项

如果使用不善,EventBus 会是一种灾难,到底是什么样的“灾难”了?大家都知道vue是单页应用,如果你在某一个页面刷新了之后,与之相关的EventBus会被移除,这样就导致业务走不下去。还要就是如果业务有反复操作的页面,EventBus 在监听的时候就会触发很多次,也是一个非常大的隐患。这时候我们就需要好好处理 EventBus 在项目中的关系。通常会用到,在vue页面销毁时,同时移除EventBus 事件监听

 // 移除特定监听

$burVue.$off('changeFather',{})

// 移除所有监听

$burVue.$off()

只监听一次

$burVue.$once('changeFather', (data) => {

  this.title = data

 })

二,$parent/$root

兄弟组件之间通信可通过共同祖辈搭桥, $parent $root。一般不建议大家使用,我们都知道组件话思想是
提⾼开发效率⽅便重复使⽤简化调试步骤提升项⽬可维护性,便于多⼈协同开发 。这就要求组件要高内聚,低耦合,此方法耦合性太高,当父子层级改变后容易产生问题,扩展性不强。
 
 
当兄弟组件有共同的父辈时。

childA:

this.$parent.$emit('changeFather', 'A')

或者

this.$root.$emit('changeFather', 'A')

childB:

this.$parent.$on('changeFather', (data) => {

      this.title = data

 })

或者

this.$root.$on('changeFather', (data) => {

      this.title = data

 })

三,$children

⽗组件可以通过$children访问⼦组件实现⽗⼦通信。

// parent
this.$children[0].xx = 'xxx'
注意: $children指的是父组件中的自定义组件集合,但是有异步组件存在的话就 不能保证⼦元素顺序。
四, $attrs/$listeners
包含了⽗作⽤域中不作为 prop 被识别 ( 且获取 ) 的特性绑定 ( class style 除外 ) 。当⼀个组件没有
声明任何 prop 时,这⾥会包含所有⽗作⽤域的绑定 ( class style 除外 ) ,并且可以通过 v
bind="$attrs" 传⼊内部组件 —— 在创建⾼级别的组件时⾮常有⽤。
// child :并未在 props 中声明 foo
<p> {{$attrs.foo}} </p>
// parent
<HelloWorld foo = "foo" />
 
四, refs
 
获取⼦节点引⽤
 
// parent
<HelloWorld ref = "hw" />
mounted() {
this.$refs.hw.xx = 'xxx'
}

五,provide/inject

注意:官方说明此种传值方式不是响应式的,但是如果父级给的是动态的也是响应式的

// parent
provide () {
 
 return { foo : 'foo' }
 
}
 
// child
 
inject : [ 'foo' ]
 
当child中自身data内也有foo时则按就近原则,data中foo生效,可采用下面写法用以区分:
 
inject:{
 
  foo2: 'foo'
 
}
 
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值