本文介绍了Vue.js 无法向 $root 元素发出事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送ChatGPT账号..我正在尝试将 $emit 事件发送给 root,但它不起作用.当我按下回车键时,它应该发送到 root 并且组件应该获取该事件并执行将其推送到数组的函数.
JS:
Vueponent('input-comp',{模板:`<div><input type="text" v-model ="textData" v-on:keyup.enter ="pushMessages"/><button v-on:click="pushMessages">发送文本</button></div>`,数据:函数(){返回 {textData : '测试消息'}},方法 : {推送消息:函数(){this.$root.$emit('message', { message: this.textData })}}})var vm = new Vue({el : '#parent',数据 : {留言:[]},方法 : {推送消息:功能(有效载荷){this.msgs.push(payload.message)}},更新(){this.$root.$on('message', this.pushMessages)}})
HTML:
<p v-for="msg in msg">{{msg}}</p><input-comp></input-comp>
解决方案 我推荐不带 $root 的事件如下:
方法:{推送消息:函数(){this.$emit('message', { message: this.textData })}}
并在父组件中处理它:
<input-comp @message="pushMessages"></input-comp>
或尝试使用 mounted
钩子代替 updated
:
挂载(){this.$root.$on('message', this.pushMessages)}
I'm trying to $emit event to root, but it's not working. When I press enter it should emit to root and component should get that event and execute function which will push it to array.
JS:
Vueponent('input-comp',{
template : `
<div>
<input type="text" v-model ="textData" v-on:keyup.enter ="pushMessages"/>
<button v-on:click="pushMessages">Send text</button>
</div>`,
data : function(){
return {
textData : 'test Message'
}
},
methods : {
pushMessages : function(){
this.$root.$emit('message', { message: this.textData })
}
}
})
var vm = new Vue({
el : '#parent',
data : {
msgs : []
},
methods : {
pushMessages : function(payload){
this.msgs.push(payload.message)
}
},
updated(){
this.$root.$on('message', this.pushMessages)
}
})
HTML:
<div id="parent">
<p v-for="msg in msgs">{{msg}}</p>
<input-comp></input-comp>
</div>
解决方案
I recommend to emit the event without $root as follows :
methods : {
pushMessages : function(){
this.$emit('message', { message: this.textData })
}
}
and in parent component handle it like :
<input-comp @message="pushMessages"></input-comp>
or try to use mounted
hook instead of updated
:
mounted(){
this.$root.$on('message', this.pushMessages)
}
这篇关于Vue.js 无法向 $root 元素发出事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论