首页 > 其他 > 详细

Vue:子组件如何跟父组件通信

时间:2018-04-15 17:57:50      阅读:180      评论:0      收藏:0      [点我收藏+]

我们知道,父组件使用 prop 传递数据给子组件。但子组件怎么跟父组件通信呢?这个时候 Vue 的自定义事件系统就派得上用场了。

使用 v-on 绑定自定义事件

每个 Vue 实例都实现了事件接口,即:

  • 使用 $on(eventName) 监听事件
  • 使用 $emit(eventName, optionalPayload) 触发事件

Vue 的事件系统与浏览器的 EventTarget API 有所不同。尽管它们运行起来类似,但是 $on 和 $emit 并不是addEventListener 和 dispatchEvent 的别名。

另外,父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。

不能用 $on 监听子组件释放的事件,而必须在模板里直接用 v-on 绑定,参见下面的例子。

下面是一个例子:

<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
Vue.component(‘button-counter‘, {
template: ‘<button v-on:click="incrementCounter">{{ counter }}</button>‘,
data: function () {
return {
counter: 0
}
},
methods: {
incrementCounter: function () {
this.counter += 1
this.$emit(‘increment‘)
}
},
})

new Vue({
el: ‘#counter-event-example‘,
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})

0

 

Vue:子组件如何跟父组件通信

原文:https://www.cnblogs.com/qjuly/p/8848276.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!