Use vm.$on to listen to event emitted from child in vue.js 2.0

前端 未结 1 1838
-上瘾入骨i
-上瘾入骨i 2020-12-29 03:22

I\'ve been through the vue.js events section on events but it seems to only give examples of how to listen to events using the vm.$on handler within html. Between that and

相关标签:
1条回答
  • 2020-12-29 04:02

    Vues documentation on $emit is not very comprehensive, however, there are a few ways to do this. Firstly you have to $emit on the vue model you want to send the message to if you want to use this.$on(), so if you are sending from a component you can emit to the direct parent using:

    this.$parent.$emit('myEvent',true);
    

    However, this can become problematic if you have a long chain of parents because you have to $emit up the child chain, so in that case you can use a Vue instance as a bus:

    // In the root as a global variable so all components have access
    var bus = new Vue({});
    

    Or if you are using single file components.

    window.bus = new Vue({});
    

    Then in the receiver:

    bus.$on('myEvent',() => {
       // Do stuff
    });
    

    And in the emitter:

    bus.$emit('myEvent',true);
    

    Finally, if you find you app getting too complex for a simple bus then you can use vuex:

    https://vuex.vuejs.org/en/index.html

    0 讨论(0)
提交回复
热议问题