1
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 ??

0

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.