VueJS 2.0 Communicating from the Parent to the Child

混江龙づ霸主 提交于 2019-12-06 12:12:14

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

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!