Vue.js 无法向 $root 元素发出事件

编程入门 行业动态 更新时间:2024-10-11 21:25:16
本文介绍了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:关键词]

本文发布于:2023-04-27 00:08:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1144900.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   事件   Vue   js   root

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!