简体   繁体   English

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

[英]Vue.js Can't emit event to $root element

I'm trying to $emit event to root, but it's not working. 我试图将$ emit事件植根,但无法正常工作。 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: JS:

Vue.component('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: 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 : 我建议不使用$ root发出事件,如下所示:

 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钩子而不是updated钩子:

  mounted(){
     this.$root.$on('message', this.pushMessages)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM