Vue2组件通讯

92 阅读1分钟

Vue2组件通讯

配置全局事件总线

  • 注册全局事件
    new Vue({
        beforeCreate(){
            Vue.protoType.%bus = this
        }
    })
    
  • 捕获事件
    mounted(){
        this.$bus.on(事件名称,数据)
    }
    
  • 发布事件
    exportData(){
        this.$bus.$emit(事件名称,数据)
    }
    
  • 事件解绑
    this.$bus.$off(事件名)
    

父子组件通讯

  • 子传父
    //子组件
    this.$emit("事件名称",数据)
    //父组件
    <children @事件名称=”getChildrenData“></children>
    getChildrenData(data){}
    
  • 父传子
    //父组件
    <children :属性名=“数据”></children>
    //子组件
    porps:["属性名"]