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

标签 javascript vue.js vuejs2 vue-component

我正在尝试将 $emit 事件发送给 root,但它不起作用。当我按下 enter 键时,它应该发送到 root 并且组件应该获取该事件并执行将其推送到数组的函数。

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:

<div id="parent">
  <p v-for="msg in msgs">{{msg}}</p>
  <input-comp></input-comp>
</div>

最佳答案

我建议在没有 $root 的情况下发出事件,如下所示:

 methods : {
    pushMessages : function(){
        this.$emit('message', { message: this.textData })
    }
  }

并在父组件中处理它:

      <input-comp @message="pushMessages"></input-comp>

或者尝试使用 mounted 钩子(Hook)而不是 updated :

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

关于javascript - Vue.js 无法向 $root 元素发出事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57869326/

相关文章:

javascript - 根据回调函数对对象进行分组

javascript - 不变违规 : Hooks can only be called inside the body of a function component

vue.js - 对于使用 Vue cli3 库的 Vuejs cli3 SPA 应用程序,SSR 构建表示 "document is not defined"

javascript - this.$refs[ ("p"+ index)].focus 不是函数

javascript - jquery仅当前一个div的文本框值不为空时才在按钮上添加新的div

javascript - 下划线/lodash : how to filter out empty properties?

javascript - vue 上下文中的 getElementsByClassName

javascript - 是否可以在同一个 package.json 文件中使用 VueJS 1 和 2?

vue.js - VueJs - 元素用户界面 : How to get change el-date-picker

javascript - vue 2 基本测试中未定义的属性