【问题标题】:Vue.js - Emit event from child to parentVue.js - 从子级向父级发送事件
【发布时间】:2019-02-22 04:45:26
【问题描述】:

我无法 $emit 将事件从子组件传递到其父组件。 我可以成功发送事件,但无法在父级中接收。

Results.vue孩子):

<a href="#" v-on:click="sendResultValues"></a>

// 

methods: {
    sendResultValues: function () {
        this.$emit('send-result-values', 'carrier');
    }
},

当我点击 &lt;a&gt; 时,我可以使用 Vue DevTools 看到 $emit 事件被触发:

但是,console.log 中没有收到任何内容,因为我的代码如下(父级):

Input.vue家长):

<search-results></search-results> //Results.vue component
<search-popover v-on:send-result-values="showResultData"></search-popover>
 //
methods: {
    showResultData: function () {
        console.log("Data received from child: ")
    }
 },

【问题讨论】:

  • results.vuesearch-popover 的组件还是 results.vuesearch-popover 的一部分?
  • 在我的 Input.vue (Parent) 文件中,我有这两个组件:&lt;search-results&gt;&lt;/search-results&gt;&lt;search-popover&gt;&lt;/search-popover&gt;
  • 不知道,似乎有效。 codesandbox.io/s/0pwz408prp 编辑沙箱,使其更类似于您的实际 vue
  • 嗯,你需要在&lt;search-results&gt;&lt;/search-results&gt; 上收听事件,而不是在&lt;search-popover&gt;&lt;/search-popover&gt;
  • 您将处理程序设置在搜索弹出窗口上,但发出事件的是搜索结果,如图所示

标签: javascript vue.js vuejs2


【解决方案1】:

您需要在search-results 组件上监听事件,而不是在search-popover 上。

Input.vue(父):

<search-results v-on:send-result-values="showResultData"></search-results>
<search-popover></search-popover>

methods: {
    showResultData: function () {
        console.log("Data received from child: ")
    }
 },

【讨论】:

    【解决方案2】:

    还有更多方法可以解决这个问题。

    1. 你可以使用 vuex.js
    2. 您可以使用 $emit 和 $on 方法

    例如

    vm.$emit('test', 'hi'); 
    vm.$on('test', function (msg) { console.log(msg) }); // => "hi"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-16
      • 2020-07-01
      • 2019-09-21
      • 2023-03-03
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多