您的位置:首页 > 产品设计 > UI/UE

父子组件通信-$emit

2017-07-04 10:39 267 查看
父子组件使用$emit和v-on时,子组件使用$emit触发,父组件在实例中v-on自定义事件监听。

注意:父组件监听子组件触发的事件,不能用
$on
侦听子组件抛出的事件,而必须在模板里直接用
v-on
绑定。

下面是官方文档给出的例子:

HTML:

<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment1="incrementTotal"></button-counter>
<button-counter v-on:increment1="incrementTotal"></button-counter>
</div>JS:
Vue.component('button-counter', {
template: '<button v-on:click="increment">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1 //组件模板中的counter
this.$emit('increment1')//触发自定义事件,这里的参数是自定义事件名称
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1  //父实例下的total
}
}
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息