整理与回顾:vue组件通信

113 阅读1分钟

vue组件的通信一直是个老生常谈的话题了。不管工作中面试中总是能碰见,今天就来整理回顾一下

1、prop

最最常见的一种,写组件是肯定要用到的

  • 父向子
// parent
<children name="tony" />

// child
props: {
    name: {
        type: String
    }
}
  • 子向父
// child
this.$emit('say', 'hello')

// parent
<children @say="e => console.log(e)" />

2、attr/attr/listrner

这个就适合隔代通信了, 包含了父级组件中 没有作为prop被识别的属性

  • 祖向孙
// grandparent
<parent name="Tom" age="50"/>

// parent
<child v-bind="$attr">

inheriAttrs: false // 注意这里要加上这个,不加的话未被声明为props的属性会被回退至上级标签上
props: {
    name: {
        type: String
    }
}

// child

<p>{{$attr.age}}</p>
  • 孙向祖
// child
this.$listener('run', 'xxx')

// grandparent
<parent name="Tom" age="50" @listener="e => console.log(e)"/>

3、#ref

// parent 
<child ref="child"/>

mounted() {  
    this.$refs.chld.xx = 'xxx' 
}

4、provide/inject

祖先对很多代的传值

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

5、eventBus

// Bus:事件派发、监听和回调管理 
class Bus { 
    constructor(){    
        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')

6、vuex

这个直接看官网吧 vuex.vuejs.org/zh/

还有很多,这里只是整理了一些常见的~