Vue.js 組件中的v-on綁定自定義事件理解
每個 Vue 實例都實現了事件介面(Events interface),即:
使用 $on(eventName) 監聽事件
使用 $emit(eventName) 觸發事件
Vue的事件系統分離自瀏覽器的EventTarget API。儘管它們的運行類似,但是$on 和 $emit 不是addEventListener 和 dispatchEvent 的別名。
另外,父組件可以在使用子組件的地方直接用 v-on 來監聽子組件觸發的事件。
下面是一個文檔上面的例子:
2017年4月11日更新
<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="increment">{{ counter }}</button>",
data: function () {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1
this.$emit("increment")
}
},
})
new Vue({
el: "#counter-event-example",
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
跟著這個例子我來談談理解,更新以前我那種錯誤的思想
先畫出理解的步驟,跟著步驟來進行理解
步驟1:
大家先看到這裡,其實在步驟4裡面的自定義標籤經過渲染之後是變成了如 步驟一 一樣的代碼,所以我們應該從這裡入手理解父子組件間事件綁定。在子組件裡面把點擊事件(click)綁定給了函數increment(即圖片裡面的步驟2),這裡容易理解,即點擊了子組件的按鈕將會觸發位於子組件的increment函數
步驟2與步驟3:
increment函數被觸發執行,在步驟2裡面執行了一句調用函數的語句
this.$emit("increment")
- 1
我們來看一下文檔
vm.$emit( event, […args] ) : 觸發當前實例上的事件。附加參數都會傳給監聽器回調
在這裡是什麼意思呢?按我自己的大白話就是這樣說的:
通過這句函數可以讓父組件知道子組件調用了什麼函數,this.$emit(『increment』) 即類似於子組件跟父組件說了一聲「hi,爸爸 我調用了我自己的increment函數」,通知父組件
步驟4:
回看一下在父組件裡面定義的自定義標籤,可以看到
v-on:increment="incrementTotal"
- 1
什麼意思呢?我們還是用大白話來解釋一下
就是說「孩子,當你調用了increment函數的時候,我將調用incrementTotal函數來回應你」
這時我們回想步驟3,在子組件我們已經使用emit來進行通知,所以,這樣就形成父子組件間的相互呼應傳遞信息,其實在開發的過程中父子組件通訊也都是使用這樣的方法,父組件傳遞信息給子組件的時候會通過props參數,通常不會直接在子組件中修改父組件傳遞下來的信息,而且通過這樣的一個鉤子去通知父組件對某些參數進行改變
步驟5:
這個就容易理解了,上一版本是本人在初學的時候寫的所以思維很不嚴謹,抱歉,歡迎大家指導批評


※Tengine-2.1.0的安裝與配置
※scrollView滾動視圖實現商城模塊(附代碼)
TAG:程序員小新人學習 |