javascript - Vue2.0的子元素自定义组件不能调用父元素的methods
本文介绍了javascript - Vue2.0的子元素自定义组件不能调用父元素的methods的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
代码如下:
<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>'
监听完事件,调用的问题,子组件只能调用自己组件内定义的方法。你可以这么样写。
Vue.component('button-counter', {
template: '<button v-on:click="incrementTotal">{{ counter }}</button>',
data: function () {
return {
counter: 0
};
},
methods: {
incrementTotal: function() {
this.counter += 1
this.$parent.incrementTotal() // 调用父组件上的方法
// 如果调用根组件的方法,this.$root.incrementTotal()
}
}
});
这篇关于javascript - Vue2.0的子元素自定义组件不能调用父元素的methods的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文