Vue中组件通信的常用方式

父组件 => 子组件:

  • 属性props

    // child
    props: { msg: String }
    // parent
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    
  • 引用refs

    // parent
    <HelloWorld ref="hw"/>
    this.$refs.hw.xx = 'xxx'
    
  • 子组件chidren

    // parent
    this.$children[0].xx = 'xxx'
    

子组件 => 父组件:自定义事件

// child
this.$emit('add', good)
// parent
<Cart @add="cartAdd($event)"></Cart>

兄弟组件:通过共同祖辈组件

通过共同的祖辈组件搭桥,$parent或$root。

// brother1
this.$parent.$on('foo', handle)
// brother2
this.$parent.$emit('foo')

祖先和后代之间

  • provide/inject:能够实现祖先给后代传值

    这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。

    // ancestor
    provide() {
       return {foo: 'foo'} //响应式
    }
    -----or----
    provide: {
       name: 'Aresn'  //非响应式
    }
    // descendant
    inject: ['foo','name']
    

    需要注意的是:

    provide 和 inject 绑定并不是可响应的。这是刻意为之的。然而,如果你传入了一个可监听的对象,那么其对象的属性还是可响应的。

    所以,上面 A.vue 的 name 如果改变了,B.vue 的 this.name是不会改变的。

任意两个组件之间:事件总线 或 vuex

  • 事件总线:创建一个Bus类负责事件派发、监听和回调管理

    // Bus:事件派发、监听和回调管理
    class Bus{
    constructor(){
    // {
    // eventName1:[fn1,fn2],
    // eventName2:[fn3,fn4],
    // }
    this.callbacks = {}
    }
    $on(name, fn){
    this.callbacks[name] = this.callbacks[name] || []
    this.callbacks[name].push(fn)
    }
    $emit(name, args){
    if(this.callbacks[name]){
    this.callbacks[name].forEach(cb => cb(args))
    }
    }
    }
    // main.js
    Vue.prototype.$bus = new Bus()
    // child1
    this.$bus.$on('foo', handle)
    // child2
    this.$bus.$emit('foo')
    

    不过因为Vue中自带了$on,和$emit所以不用这么写,直接new一个Vue挂载到原型上就可以

  • vuex:创建唯一的全局数据管理者store,通过它管理数据并通知组件状态变更

posted @ 2019-05-01 10:33  仲吕  阅读(213)  评论(0)    收藏  举报