Vue.js/Laravel: How to pass data between multiple components

Viewed 97
require('./bootstrap');

window.Vue = require('vue');

Vue.component('exampleComponent1', require('./components/exampleComponent1.vue'));
Vue.component('exampleComponent2', require('./components/exampleComponent2.vue'));

const app = new Vue({
    el: '#app'
});

from the above code, I want to pass data from exampleComponent1 to exampleComponent2 when some event has occurred in exampleComponent1.

What is the optimal solution for this ??

2 Answers

The key here is to set their parent component as the one receiving from the first (using emit) and sending to the second (using props):

const component1 = Vue.component('component1', { 
  template: '#component1',
  data() { return { name: '' } },
  methods: {
    updateName() { this.$emit("namechanged", this.name); }
  }
});

const component2 = Vue.component('component2', { 
  template: '#component2',
  props: ['name'],
});

new Vue({
  el: "#app",
  components: { component1, component2 },
  data() { return { name: '' } },
  methods: {
    updateName(newName) { this.name = newName; }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div><component1 @namechanged="updateName"/></div>
  <div><component2 :name="name"/></div>
</div>

<template id="component1"><input v-model="name" @input="updateName"/></template>

<template id="component2"><p>Input From component 1: {{name}}</p></template>

You can use a Event Bus for this.

// in some global file
const EventBus = new Vue();

// creating or emitting event
EventBus.$emit('someEvent', 'some-data')

// listen to the event
EventBus.$on('someEvent', function(data) {
  console.log(data) // 'some-data
})
Related