如何在没有v-on指令的情况下从emit事件中获取值?

时间:2018-05-04 16:34:22

标签: vue.js

我有两个组成部分:父母和儿童。

在Child组件中,我创建用户事件:

someMethod() {
    this.$emit('init-event', 100)
}

父组件:

getChildEventValue() {
    // how now get value from event 'init-event' without v-on directive in template?
}

1 个答案:

答案 0 :(得分:0)

典型&简单的方法是简单地使用事件总线。有几种不同的方法可以创建全局事件总线。在我的设置中,我按如下方式进行操作

在主要的js ......

Vue.prototype.$Bus = new Vue(); 

然后在您的孩子组件,或兄弟姐妹或任何地方......

this.$Bus.$emit('myEvent');

然后在您的其他组件中收听该事件。也许是挂钩......

mounted(){
        this.$Bus.$on('myEvent', function(){
            console.log('receive the event!')
        } );
    }