子组件 ═══>向父组件传递数据时,就要用到自定义事件
v-on除了监听DOM事件外,还可以用于组件之间的自定义事件
子组件用$emit()来触发事件,父组件用$on()来监听子组件的事件
<div id="app">
<p>总数:{{ 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>
网友评论