组件间传值、通信

126 阅读1分钟

记录这篇笔记用以加深印象以及后续翻阅巩固。

1、父子组件

1、父组件给子组件传值

  • 属性props
//child
props:{msg:String}

//parent
<child mag='北海,你要多想'>
  • 引用refs获取子组件实例阿斯蒂芬
//parent
<child ref='child'>
this.$refs.child.attr = '北海,你要多想'阿斯蒂芬
  • $children获取子组件实例

注意$children不保证顺序,不是响应式的(cn.vuejs.org/v2/api/#vm-…

//parent
this.$children[0].attr = '北海,你要多想'

##2、子组件给父组件传值

  • 自定义事件 用$emit去派发事件,然后在父组件引用子组件的地方监听该事件,监听者仍然是子组件实例,就是谁发布,谁监听
//child
this.$emit('hi',hello)

//parent
<child @hi='listenFn($event)'>
listenFn(e){
condole.log(e)
}

#2、兄弟组件 通过共同的祖辈组件搭桥parentparent或 root (谁发布,谁监听)

//brother1喊
this.$parent.$emit('hi')

//brother2听
this.$parent.$on('hi',()=>{
  console.log('hi,我听到了')
})

#3、祖先和后代

  • provide/inject:能够实现祖先给后代传值 祖先提供值,孩子注入值,只适用于祖先给后代传值,单向的,只适用于组件库的开发,平时不要用也没必要
//ancestor
//provide可以用对象也可以用函数,跟data很类似
provide(){
  return {hibaby:'孩子,你们有兄弟'}
}

//descendant
//inject跟props用法很类似
//这个传递的值虽然是响应式,但官方建议不要去改,如果一定要改,那就在传递这个值的时候,顺便传一个可以改变这个值的函数进来
inject:['hibaby']

小技巧:传祖先组件的实例:

provide(){
  that:this
  //注意这里只能用函数,如果用对象那this指向可能有问题
}

#4、任意两个组件之间

  • 事件总线:创建一个Bus类负责事件派发、监听和回调管理
//创建一个独立的实例,专门用来监听和派发事件
//平时工作中这么写,是因为vue已经实现了bus类的功能
Vue.prototype.$bus = new Vue()
//Bus类
class Bus{
  constructor(){
    {
      event1:[fn1,fn2],
      event2:[fn3,fn4],
    }
    this.callbacks = {}
  }
  $on(name,fn){
    this.callbacks[name] = this.callbacks[name] || []
    this.callbacks[name].push(fn)
  }
   $emit(name,fn){
    if(this.callbacks[name]){
       this.callbacks[name].forEach(cb => cb(args))
  }
}

//main.js
Vue.prototype.$bus = new Bus()

//child1
this.$bus.$emit('hiBrother')

//child2
this.$bus.$on('hiBrother',hearYouFn)
  • vuex:创建唯一的全局数据管理者store,通过它管理数据并通知组件状态变更