1. 程式人生 > >Vue:子組件如何跟父組件通信

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

dev table noop div listener developer tle number lin

我們知道,父組件使用 prop 傳遞數據給子組件。但子組件怎麽跟父組件通信呢?這個時候 Vue 的自定義事件系統就派得上用場了。

使用 v-on 綁定自定義事件

每個 Vue 實例都實現了事件接口,即:

  • 使用 $on(eventName) 監聽事件
  • 使用 $emit(eventName, optionalPayload) 觸發事件

Vue 的事件系統與瀏覽器的 EventTarget API 有所不同。盡管它們運行起來類似,但是 $on$emit 並不是addEventListenerdispatchEvent 的別名。

另外,父組件可以在使用子組件的地方直接用 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:子組件如何跟父組件通信