vue组件化通信

464 阅读1分钟

组件化传值、通信

1.父组件 => 子组件

属性props

// parent
  <keBe msg="welocme to my life" />
// child
  props: {msg:String}

引用refs

// parent
 <KeBe ref="hw" />
 
 this.$refs.hw.xx

2.子组件 => 父组件

自定义事件

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

//parent
<Cart @add="cartAdd($event)"></Cart>

3.兄弟组件传值

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

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

//brother2
this.$parent.$emit('foo')

4.祖先和后代之间

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
    }
}

<!--使用-->
<h1 @click="dispatch('hello','hello,world')">{{msg}}</h1>

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

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

事件总线:创建一个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)]
        }
    }
}