Skip to content
This repository was archived by the owner on May 24, 2019. It is now read-only.

Communication between Components

Pascal edited this page Aug 31, 2017 · 4 revisions

https://github.com/oanstein/VueJS-Complete-Guide-Code/tree/e8aac9a055f14c5c895a193c1b9c9d46010261af/08_communication_btn_cmps


Example: eventBus & $emit

/src/main.js

import Vue from 'vue'
import App from './App.vue'

export const eventBus = new Vue({
  methods: {
    changeAge (age) {
      this.$emit('ageWasEdited', age);
    }
  }
});

new Vue({
  el: '#app',
  render: h => h(App)
})

/src/components/UserEdit.vue#L20

<template>
    <div class="component">
        <h3>You may edit the User here</h3>
        <p>Edit me!</p>
        <p>User Age: {{ userAge }}</p>
        <button @click="editAge">Edit Age</button>
    </div>
</template>

<script>
  import { eventBus } from '../main';
  export default {
    props: ['userAge'],
    methods: {
      editAge() {
        this.userAge = 30;
        // this.$emit('ageWasEdited', this.userAge);
        // eventBus.$emit('ageWasEdited', this.userAge);
        eventBus.changeAge(this.userAge); // This method is defined in eventBus and triggers 'ageWasEdited'
      }
    }
  }
</script>

<style scoped>
    div {
        background-color: lightgreen;
    }
</style>

/src/components/UserDetail.vue#L35

<template>
    <div class="component">
        <h3>You may view the User Details here</h3>
        <p>Many Details</p>
        <p>User Name: {{ switchName() }}</p>

        <p>User Age: {{ userAge }}</p>
        
        <button @click="resetName">Reset Name</button>
        <button @click="resetFn()">Reset Name</button>
    </div>
</template>

<script>
  import { eventBus } from '../main';
  export default {
    props: {
      // Other Code
      userAge: Number
    },
    methods: {
      // Other Code
    },
    created () {
      // Triggered when $emit 'ageWasEdited'
      eventBus.$on('ageWasEdited', (age) => {
        this.userAge = age;
      });
    }
  }
</script>

Index

Clone this wiki locally