0

Let's say I have the following component hierarchy:

  • App.vue
    • vue-router's router-view tag
      • Home.vue: the home page
        • PopularAudioList.vue
      • About.vue some static page
    • Player.vue: an always-on-top audio player that can be used throughout the site. Playback isn't interrupted when switching pages. It has visible play/stop/volume controls.

PopularAudioList.vue renders a list of audio files that users can choose from, and a play button for each item. Each play button emits a audio-file-chosen event with a URL parameter. I know how to make the component's parent, Home.vue, hook in to this event. But I'd like Player.vue to catch it, since that's the component that will be controlling audio playback.

What's the best way to propagate the event there? I could try to make Home.vue re-emit the event to App.vue, which would need to pass it to Player.vue. But that seems horribly inefficient, it smells like bad architecture, and vue-router might make this difficult.

Should I reorganize my architecture to create a more direct relation between PopularAudioList.vue and Player.vue to make this work? Are events even the right choice here?

tony19
  • 125,647
  • 18
  • 229
  • 307
Pieter
  • 31,619
  • 76
  • 167
  • 242
  • probably like this: inside `player.vue`, uses `this.$root.on('your-event', handler())`, or use [event bus](https://stackoverflow.com/questions/38064054/vue-js-global-event-bus) – Sphinx Aug 02 '18 at 16:11
  • @thanksd, the approach `this.$root.$emit` and `this.$root.$on` should work also, but after google it, it seems much less developers mentioned this solution. are there any disadvantages? Caused by can't use it in the template by `v-on`? – Sphinx Aug 02 '18 at 18:29
  • 1
    @Sphinx There's nothing necessarily wrong with handling events through the root instance. It's effectively the same as using a bus (which is described in the post I linked). I think most people prefer to use bus instances because it's more explicitly clear that the function of the instance is for global event handling. In larger applications, you also might have multiple bus instances for different types of events. But yeah, like you mentioned, one of the downsides of using a bus or the root is that they don't use `v-on`, which makes it harder to see the flow of data in your app. – thanksd Aug 02 '18 at 18:57
  • Bingo. I think I'll either take the Vuex or `this.$root.$emit` approach then! – Pieter Aug 02 '18 at 19:13

0 Answers0