码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-04-15 18:02:33      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:template   模板   如何   fun   temp   ram   一个   class   传递   

我们知道,父组件使用 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:子组件如何跟父组件通信

标签:template   模板   如何   fun   temp   ram   一个   class   传递   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!