代码如下:
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:click="incrementTotal"></button-counter>
<button-counter v-on:click="incrementTotal"></button-counter>
</div>
<script>
Vue.component('button-counter', {
template: '<button >{{ counter }}</button>',
data: function () {
return {
counter: 0
};
}
});
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1;
}
}
});
</script>
为什么button-counter添加的click事件不能调用父元素的methods里面的方法呢?
监听事件不能在组件上监听,
<button-counter v-on:click="incrementTotal"></button-counter>
这样写不对, Vue 会渲染组件的模板(template),所以应该在模板上监听,template: '<button v-on:click="incrementTotal">{{ counter }}</button>'
监听完事件,调用的问题,子组件只能调用自己组件内定义的方法。你可以这么样写。