Vue组件通讯

组件通信常用方式

  • props

  • event

  • vuex

自定义事件

  • 边界情况

  1. $parent

  2. $children

  3. $root

  4. $refs

  5. provide/inject

  • ⾮prop特性

  1. $attrs

  2. $listeners

模拟vue $bus

// 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')

 

实践中通常⽤Vue代替Bus,因为Vue已经实现了相应接⼝  

 

$bus

定义$bus
import Vue from 'vue'
const bus = new Vue()
export default bus
发送信息
import bus from '@/utils/bus
bus.$emit('message', 'hello');

接收信息

import bus from '@/utils/bus'
bus.$on('message', (e) => {
    console.log(e)
})

$attrs/$listeners

包含了⽗作⽤域中不作为 prop 被识别 (且获取) 的特性绑定 ( class 和 style 除外)。当⼀个组件没有 声明任何 prop 时,这⾥会包含所有⽗作⽤域的绑定 ( class 和 style 除外),并且可以通过 v- bind="$attrs" 传⼊内部组件——在创建⾼级别的组件时⾮常有⽤。

// child:并未在props中声明foo
<p>{{$attrs.foo}}</p>
// parent
<HelloWorld foo="foo"/>
$listeners
// child
<p v-on="$listeners">ssssssssssssssssssssddddddddd</p>
// parent
<msgOne type="good" @click="onClick"></msgOne>

 

posted @ 2020-04-14 17:23  青柠咖啡  阅读(105)  评论(0)    收藏  举报