网络编程
位置:首页>> 网络编程>> JavaScript>> Vue $emit()不能触发父组件方法的原因及解决

Vue $emit()不能触发父组件方法的原因及解决

作者:小小米粒吖  发布时间:2024-05-28 16:10:26 

标签:Vue,emit,触发,父组件

$emit传入的事件名称只能使用小写,不能使用大写的驼峰规则命名

如果修改后还是不行的话,就改用:

this.$parent.Event (Event为父组件中的自定义方法)

补充知识:Vue.js 使用 $emit 触发事件填坑

vue的组件内触发外部事件不起作用

vue的组件内触发自定义事件(发外部事件)不起作用

今天学习vue的自定义组件功能,在组件内部触发一个事件,在使用组件的地方使用v-on绑定这个事件,然而触发一直不生效,检查了很多遍的代码都没看出什么问题,代码如下:


<div id="app">
<button v-on:click="IncrHandle">增加</button>
<input v-model="total" placeholder="请输入内容" />
<child v-bind:count="total" v-on:onIncr="IncrHandle"></child>
</div>
Vue.component("child",{
props:['count'],
template:"<button v-on:click='incr'>增加{{count}}</button>",
data: function(){
return {
 count: 0
}
},
methods:{
incr: function(){
 this.$emit('onIncr')
 this.count += 1
}
}
})
new Vue({
el:"#app",
data:{
total: 0
},
methods:{
IncrHandle:function(){
 this.total += 1
 total("增加1")
},
DncrHandle:function(){
 this.total -= 1
}
}
})

经过无数的验证,终于找到了解决办法:

保证待传递的事件名称为纯小写。不可以使用驼峰j格式。

即:

将v-on:onIncr改为v-on:onincr,将this.emit(′onIncr′)改为this.emit(&#x27;onIncr&#x27;)改为this.emit( ′ onIncr ′ )

改为this.emit(‘onincr')

来源:https://blog.csdn.net/weixin_41472431/article/details/89434160

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com