vue组件通信

307 阅读1分钟

父子组件

父组件 => 子组件

  • props属性
// child
props: {
    msg: {
        type: String
    }
}

// parent
<HelloMessage msg="hello world"/> 

  • refs引用
// child
methods:{
    showMessage() {
        console.log(this.msg)
    }
}
// parent
<HelloMessage refs="hm"/> 
this.$refs.hm.showMessage()

子组件 => 父组件

  • 自定义事件
// child
this.$emit('getChild')

// parent
<HelloMessage @getChild="getChild"/>

兄弟组件

  • 通过共同祖辈组件搭桥通信
// brother1
this.$parent.$on('foo')
// brother2
this.$parent.$emit('foo')

祖先和后代通信

由于嵌套层数过多,传递props不切实际,vue提供了provide/inject Api完成传递

  • provide/inject 实现祖先给后代传值
// ancestor
provide() {
    return {
        foo: 'foo'
    }
}

// descendant
inject:['foo']

注意:provide/inject主要是给高阶组件库/插件提供用例。并不推荐直接应用到项目代码中。另外,这样的方式不用用于后代给祖先传值

  • dispatch: 后代给祖先传值
// 在child中自定义广播事件
function dispatch(eventName, data) {
    let parent = this.$parent
    while(parent) {
        if(parent) {
            // 触发事件
            parent.$emit(eventName, data)
            // 递归
            parent = parent.$parent
        }else {
            break
        }
    }
}

// child中 helloMessage.vue
<button @click="dispatch('foo', {foo: 'foo1'})"/>

// parent app.vue
this.$on('foo', this.getChildInfo)

任意两个组件传递

  • 事件总线 Bus
window.bus = new Bus()

// child1
window.bus.$emit('busEvent')

// child2
window.bus.$on('busEvent',this.getBusInfo())

vuex