Day 4 of Vue.js

Child to Parent Communication

A child can emit a message just like the example in yesterday’s post.
Here’s another example:

Vue.component('coupon', {
template: '<input type="text" placeholder="enter your code" />',

methods: {
onCouponApplied() {
this.$emit('applied'); //@applied="onCouponApplied"
}
}

});

new Vue({
el: '#root',

data: {
couponApplied: false
},

methods: {
onCouponApplied() {
this.couponApplied = true;
}
}
});

this.$emit('applied) will announce the event applied to its parent <coupon @applied="onCouponApplied"></coupon>, which will set onCouponApplied to true.

Sibling Communication (or to-anyone communication)

The usual practice is to initialize a new Vue instance as a window.Event, then you can use Event.$emit and Event.$on to broadcast and listen for the event.
Jeffrey suggested using a more intuitive api:

window.Event = new class {
    constructor() {
        this.vue = new Vue();
    }

    fire(event, data = null) {
        this.vue.$emit(event, data);
    }

    listen(event, callback) {
        this.vue.$on(event, callback);
    }
}

To broadcast:

Vue.component('coupon', {
    template: '<input placeholder="enter your code" @blur="onCouponApplied">',
    methods: {
        onCouponApplied() {
            Event.fire('applied'); //@applied="onCouponApplied"
        }
    }
});

To listen:

Vue.component('notification', {
    template: `
    <div v-if="shouldShow" class="notification is-primary">
        <button class="delete"></button>   
    </div>
    `,

    data() {
        return {
            shouldShow: false
        }
    },
    created() {
            Event.listen('applied', () => this.shouldShow = true);
        }
})

Very useful.

Leave a Reply

Your email address will not be published. Required fields are marked *