组件的6种通信方式

218 阅读1分钟

props

适用的场景:父子组件通信 书写方式:

props:['todos']
props:{
    todos:{
        type : Array,
        default:[]
    }
}

自定义事件 $emit

适用的场景:子组件给父组件传递数据/调用函数 onon 与 emit

// 子组件
<button @click="btnClick">点击传值</button>
btnClick(){
    let num = 10 
    this.$emit('aaa',num)
}

// 父组件
<child @aaa="bbb"></child>

bbb(num){
    console.log(num)
}

全局事件总栈

适用场景:万能 Vue.prototype.$bus = this;

Vuex

适用场景:万能

插槽

适用场景:父子组件通信(一般结构)

pubsub-js

发布与订阅 --- 在React框架中用的比较多 适用场景:万能