13.组件通信(二)

未匹配的标注
  • 本系列文章为laracasts.com 的系列视频教程——Learn Vue 2: Step By Step 的学习笔记。若喜欢该系列视频,可去该网站订阅后下载该系列视频,支持正版
  • 视频源码地址:github.com/laracasts/Vue-Forms
  • 项目初始版本为Vue 2.1.3,教程还在更新中。

本节说明

  • 对应第 13 小节:Component Communication Example 2:Event Dispatcher

本节内容

上一节我们学习了简单的父组件与子组件之间的通信,但是当有多个子组件,并且其中一个子组件想要通知其他子组件时,我们又该怎么做呢?

main.js

window.Event = new Vue();

Vue.component('coupon',{
    template:'<input placeholder="enter your coupon code" @blur="onCouponApplied">',

    methods: {
        onCouponApplied() {
            Event.$emit('applied');
        }
    }
});

new Vue({
    el:'#root',

    data: {
        couponApplied:false
    },

    created(){
        Event.$on('applied',() => alert('Handing it!'));
    }
});

请注意,我们实例化了一个共用的Vue实例,然后我们可以借助这个共用的实例,在任一组件上进行触发和监听事件。这样一来,组件间就可以互相通信。应用组件:

index.html

<!DOCTYPE html>

<html>
    <head>
    </head>

    <body>
        <div id="root" class="container">
            <coupon></coupon>

            <h1 v-if="couponApplied">Your coupon is applied.</h1>
        </div>

        <script src="https://unpkg.com/vue@2.1.3/dist/vue.js"></script>

        <script src="main.js"></script>
    </body>
</html>

查看效果:
file
我们还可以对原生的 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);
    }
}

Vue.component('coupon',{
    template:'<input placeholder="enter your coupon code" @blur="onCouponApplied">',

    methods: {
        onCouponApplied() {
            Event.fire('applied');
        }
    }
});

new Vue({
    el:'#root',

    data: {
        couponApplied:false
    },

    created(){
        Event.listen('applied',() => alert('Handing it!'));
    }
});

最终效果:
file

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~