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>
查看效果:
接下来我们来进行父组件与子组件之间的通信:子组件触发事件,父组件监听到,然后触发动作。
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
。最终效果: