Vue兄弟组件间通信获取$on里的数据

在Vue中我们有时候会用到组件间通信,通过$emit绑定事件,然后通过$on触发,那么怎样获取到$on里的数据呢?

比如组件A中,我们想通过$emit向组件B传递this.value值,在组件B中通过$on获取,我们发现在$on事件外部根本无法获取到组件A传来的数据。

// 组件A:

methods:{
    sure() {
      bus.$emit("blur", this.value);
    }
}

// 组件B:

created() {
    bus.$on('blur', arg => {
        this.time = arg    
    })
    console.log(this.time)    // undefined
}

那么究竟应该怎么做才能获取到arg呢,我们可以使用app作为中间件就能获取到:

// 组件B:

created() {
    bus.$on('blur', arg => {
        app.time = arg    
    })
    console.log(app.time)    // 8:30
}

猜你喜欢

转载自blog.csdn.net/weixin_42604536/article/details/87928450
今日推荐