vue怎么调用子元素的方法_javascript - Vue2.0的子元素自定义组件不能调用父元素的methods...

问 题

代码如下:

{{ total }}

Vue.component('button-counter', {

template: '{{ counter }}',

data: function () {

return {

counter: 0

};

}

});

new Vue({

el: '#counter-event-example',

data: {

total: 0

},

methods: {

incrementTotal: function () {

this.total += 1;

}

}

});

为什么button-counter添加的click事件不能调用父元素的methods里面的方法呢?

解决方案

监听事件不能在组件上监听, 这样写不对, Vue 会渲染组件的模板(template),所以应该在模板上监听,template: '{{ counter }}'

监听完事件,调用的问题,子组件只能调用自己组件内定义的方法。你可以这么样写。

Vue.component('button-counter', {

template: '{{ counter }}',

data: function () {

return {

counter: 0

};

},

methods: {

incrementTotal: function() {

this.counter += 1

this.$parent.incrementTotal() // 调用父组件上的方法

// 如果调用根组件的方法,this.$root.incrementTotal()

}

}

});

扫一扫关注IT屋

微信公众号搜索 “ IT屋 ” ,选择关注与百万开发者在一起

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值