组件通信大总结

组件交互(传值,交互)分类:

父组件 => 子组件:

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

    引用refs
    // parent 
    
    this.$refs.hw.xx

 

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

 // child 
 this.$emit('add', good)
 // parent
 

 

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

 通过共同的祖辈组件搭桥,$parent或$root。
 // brother1 
 this.$parent.$on('foo', handle)
 // brother2 
 this.$parent.$emit('foo')

 

祖先和后代之间

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

// ancestor 
provide() {
    return {foo: 'foo'}
}
// descendant 
inject: ['foo']

 

dispatch:后代给祖先传值

// 定义一个dispatch方法,指定要派发事件名称和数据
function dispatch(eventName, data) {
    let parent = this.$parent
    // 只要还存在父元素就继续往上查找
    while (parent) {
        // 父元素用$emit触发
        parent.$emit(eventName,data)
        // 递归查找父元素
        parent = parent.$parent
    }
}
// 使用,HelloWorld.vue

{ { msg }}

// App.vue this.$on('hello', this.sayHello)

 

任意两个组件之间:事件总线 或 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')

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

 

直接上案例,看效果:

组件通信大总结_第1张图片

GrandGrandChild.vue组件:



 

GrandChild1.vue组件:



 

GrandChild2.vue组件:



 

Child1.vue组件:





Child2.vue组件:




 

Index.vue组件:




 

你可能感兴趣的:(vue高级)