[Vuejs]-Adding component to parent from child in vue

1👍

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.

Leave a comment