VueJS 2.0 Communicating from the Parent to the Child

淺唱寂寞╮ 提交于 2019-12-12 10:06:59

问题


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


回答1:


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




回答2:


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>


来源:https://stackoverflow.com/questions/42983376/vuejs-2-0-communicating-from-the-parent-to-the-child

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