Vue中父組件使用prop向子組件傳遞數據,那么子組件向父組件使用什么方式傳遞信息:自定義事件。
1.先來看官網上面教程
每個 Vue 實例都實現了事件接口,即:
- 使用
$on(eventName)
監聽事件 - 使用
$emit(eventName, optionalPayload)
觸發事件
<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
}
}
})
2.功能解釋:
當子組件click出發一個效果,子組件事件(incrementTotal)命名為"increment"放入父組件中觸發($emit('increment'))。
以下為個人理解:子組件的事件(incrementTotal)是獨立不可共享的,使用事件綁定(v-on)給子組件事件包裝一層可以被父組件接收的外衣,
實際上父組件還是要使用子組件事件(incrementTotal),當然其內部邏輯可自定義。
以上內容為個人學習所感,如有錯誤請指正,勿噴。