子組件 ═══>向父組件傳遞數(shù)據(jù)時(shí),就要用到自定義事件
v-on除了監(jiān)聽DOM事件外,還可以用于組件之間的自定義事件
子組件用$emit()來觸發(fā)事件,父組件用$on()來監(jiān)聽子組件的事件
<div id="app">
<p>總數(shù):{{ total }}</p>
<ceshi @increase="handleGetTotal" @reduce="handleGetTotal"></ceshi>
</div>
<script>
import Vue from 'vue'
Vue.component('ceshi', {
template: ' \
<div> \
<button @click="handleIncrease">+1</button> \
<button @click="handleReduce">-1</button> \
</div>',
data: function () {
return {
counter: 0
}
},
methods: {
handleIncrease: function () {
this.counter++;
this.$emit('increase', this.counter);
},
handleReduce: function () {
this.counter--;
this.$emit('reduce', this.counter);
},
}
});
var app = new Vue({
el: '#app',
data: {
total: 0
},
methods: {
handleGetTotal: function (total) {
this.total = total;
}
}
})
</script>