Reputation: 6987
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
Upvotes: 2
Views: 952
Reputation: 4443
To communicate from parent to child you can use components props.
If you have a more deeper communication (parent communicate with little-little...-child) you can use the busEvent mention by @WilomGfx.
Code for communication from parent to child :
Vue.component('modal', {
template: '<div :class="[ modalClass, {\'is-active\' : isActive }]">' +
'Hello Word !' +
'</div>',
data() {
return {
modalClass: 'modal'
}
},
props: {
isActive: { type: Boolean, default: false }
}
});
new Vue({
el: '#root',
data() {
return {
isActive: false,
}
},
methods: {
showModal() {this.isActive = true },
}
});
.is-active {
color: red;
}
<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="root">
<modal :is-active="isActive"></modal>
<button @click="showModal">Show Modal (going red when prop isActive is true)</button>
</div>
Upvotes: 1
Reputation: 2013
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', (params) => {})
this.bus.$emit('event', params)
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
Upvotes: 3