簡體   English   中英

Vue.js - 從子級向父級發出事件

[英]Vue.js - Emit event from child to parent

我無法將$emit從子組件發送到它的父組件。 我可以成功發送事件,但不能在父級中接收它。

Results.vue孩子):

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

// 

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

當我點擊<a>時,我可以使用 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: ")
    }
 },

您需要在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: ")
    }
 },

有更多方法可以解決此問題。

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

例如

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

在我看來,你應該在父端做事件聲明方程。

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

點擊事件不應該是那個,它應該是發送結果值。 所以結果是

<a href="#" v-on:send-result-values="sendResultValues"></a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM