1. 程式人生 > >vue2.0中v-on綁定自定義事件的理解

vue2.0中v-on綁定自定義事件的理解

按鈕 自定義事件 監聽器 code 自定義 pre strong 數據 解耦

vue中父組件通過prop傳遞數據給子組件,而想要將子組件的數據傳遞給父組件,則可以通過自定義事件的綁定。

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

1、使用 $on(eventName) 監聽事件

2、使用 $emit(eventName) 觸發事件

父組件可以在使用子組件的地方直接用 v-on 來監聽子組件觸發的事件。

html代碼:

1 <div id="counter-event-example">
2   <p>{{ total }}</p>
3   <button-counter v-on:increment="incrementTotal"
></button-counter> 4 <button-counter v-on:increment="incrementTotal"></button-counter> 5 </div>

css代碼:

 1 Vue.component(‘button-counter‘, {
 2   template: ‘<button v-on:click="increment">{{ counter }}</button>‘,
 3   data: function () {
 4     return {
 5       counter
: 0 6 } 7 }, 8 methods: { 9 increment: function () { 10 this.counter += 1 11 this.$emit(‘increment‘) 12 } 13 }, 14 }) 15 new Vue({ 16 el: ‘#counter-event-example‘, 17 data: { 18 total: 0 19 }, 20 methods: { 21 incrementTotal: function () { 22 this.total += 1
23 } 24 } 25 })

在子組件裏面把點擊事件(click)綁定給了函數increment。點擊子組件的按鈕將會觸發位於子組件的increment函數。

this.$emit(‘increment‘) 這是觸發當前實例上的事件。附加參數都會傳給監聽器回調。

子組件在調用了increment函數的時候,通過$emit來通知父組件。這樣就形成父子組件間的相互呼應傳遞信息。

在平常的組件通訊,父組件是通過props參數對子組件進行傳遞,而子組件向父組件傳遞則可以使用自定義事件了。

這樣,父組件和子組件已經解耦,子組件收到的是父組件內部的實現

vue2.0中v-on綁定自定義事件的理解