Moshe Moshe -4 years ago 123
Javascript Question

VueJS 2.0 Communicating from the Parent to the Child

I'm sure there is a simple way to do this, but I can't figure it out.

In my html file I have the following button:

<button @click="showModal">Show Modal</button>


Clicking that button runs the following method:

new Vue({
el: '#root',
methods: {
showModal() { Event.$emit('showModal'); },
}
});


What I want to happen when I click on that button is to toggle a class in a modal component. Here is the relevant code for the component:

Vue.component('modal', {

template: `
<div :class="[ modalClass, {'is-active' : isActive }]">
ETC...
</div>
`

data() {
return {
isActive: false,
modalClass: 'modal'
}
}


I am new to VueJS and am trying to figure out how to communicate in Vue. I can't seem to figure out the next step. What do I have to do so that isActive is set to true when the button is clicked?

Thanks for any help you can offer.

All the best,

Moshe

Answer Source

In your main.js (or where ever you instantiate your Vue app)

You can use a plain vue instance as an eventbus

Vue.prototype.bus = new Vue();

this way you can use it as so :

this.bus.$on('event', (data) => {})

this.bus.$emit('event',data)

Check out one of my vue project on github as an example, i the eventbus a lot. https://github.com/wilomgfx/vue-weather

Also check out this free amazing series on VueJS 2, its really great : https://laracasts.com/series/learn-vue-2-step-by-step

Full blown example using the op's question:

https://codepen.io/wilomgfx/pen/OpEVpz?editors=1010

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download