ThomasD
ThomasD

Reputation: 2494

adding component to parent from child in vue

The structure of my root component is something like:

<Header />
<router-view />
<Footer />

On some pages I would like to add some additional buttons to the header by passing a component with buttons from the child component of the router-view to the Header-component. Since we are talking about buttons, I need to be able to listen for the click events and handle the events in the child component.

I know how to pass information from parent to child and I know how to emit events from child components to be handled by parent components, but this doesn't seem like the right way (I might be wrong).

I might be missing something, but I cannot figure out how to pass components from CHILD to PARENT.

Any ideas?

Upvotes: 0

Views: 202

Answers (1)

HMilbradt
HMilbradt

Reputation: 4639

Instead of trying to pass data directly between components like this, you should take a look at creating an event bus. In this case, it's just another Vue instance, but you can subscribe to and emit events on it just like a regular Vue instance, allowing 2 way data communication.

From the article:

// ./event-bus.js
import Vue from 'vue';
export const EventBus = new Vue();

Sending events on the bus:

// PleaseClickMe.vue
<template>
  <div class="pleeease-click-me" @click="emitGlobalClickEvent()"></div>
</template>

<script>
// Import the EventBus we just created.
import { EventBus } from './event-bus.js';

export default {
  data() {
    return {
      clickCount: 0
    }
  },

  methods: {
    emitGlobalClickEvent() {
      this.clickCount++;
      // Send the event on a channel (i-got-clicked) with a payload (the click count.)
      EventBus.$emit('i-got-clicked', this.clickCount);
    }
  }
}
</script>

Listening to events on the bus:

// Import the EventBus.
import { EventBus } from './event-bus.js';

// Listen for the i-got-clicked event and its payload.
EventBus.$on('i-got-clicked', clickCount => {
  console.log(`Oh, that's nice. It's gotten ${clickCount} clicks! :)`)
});

Now you can just check the URL and change the buttons depending on what route is displayed.

Upvotes: 1

Related Questions