12.组件通信(一)

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

本节说明

  • 对应第 12 小节:Component Communication Example 1:Custom Event

本节内容

接下来的两小节我们来学习组件之间的通信。我们新建一个组件coupon

main.js

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

    methods: {
        onCouponApplied() {
            alert('applied!');
        }
    }
});

new Vue({
    el:'#root'
});

应用组件:

index.html

<!DOCTYPE html>

<html>
    <head>
    </head>

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

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

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

查看效果:
file
接下来我们来进行父组件与子组件之间的通信:子组件触发事件,父组件监听到,然后触发动作。

main.js

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

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

new Vue({
    el:'#root',

    data: {
        couponApplied:false
    },

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

index.html

<!DOCTYPE html>

<html>
    <head>
    </head>

    <body>
        <div id="root" class="container">
            <coupon @applied="onCouponApplied"></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>

this.$emit('applied')会触发在当前实例上的applied事件,而父组件监听到applied事件被触发,会运行父组件上的onCouponApplied()方法,从而更改couponApplied属性值为true。最终效果:
file

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

上一篇 下一篇
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~