2016-10-27 47 views
0

所以我在Vue上開發應用程序。我在組件之間發送和接收數據時遇到問題。已經嘗試過$dispatch/$broadcast$emit/$on,但現在仍在工作。我想將選定的active_clubClubSelection.vue發送到vue_main.js。我的應用程序的Vue 2 - 組件之間的通信(發送和接收數據)

Vue version: 2.0.3

結構:

  1. vue_main - 主要VUE文件
    1. HeaderElement.vue(孩子vue_main的)
      1. ClubSelection.vue(孩子HeaderElement

需要從ClubSelection發送active_club到vue_main。

ClubSelection.vue

<script> 

    export default{ 
     props: [ 
      'club', 'title' 
     ], 
     created(){ 

      //Get club list 
      this.$http.get('/api/clubs', function(data) { 
       this.clubs = data; 
       console.log(data); 

       //read active club from parent 
       this.selected = this.$parent.$parent.active_club; 
      }); 

     }, 
     data(){ 
      return{ 
       clubs: [], 
       selected: null, 
      } 
     }, 
     watch: { 
      selected: function(v) { 
       this.club = v; 

       //Post to database selected club 
       this.$http.post('/api/clubs/' + v + '/active') 

      }, 
      club: function(v) { 
       this.selected = v; 

       //Change active_club at parent (THIS NOT WORKING) 
//    this.$emit('active_club', v); 
//    this.$parent.active_club = v; 
       club.$emit('active_club', v); 

      }, 
     } 

    } 
</script> 

vue_main.js

const app = new Vue({ 
    router, 
    data() { 
     return { 
      user: [], 
      active_club: null, 
      ranking: null 
     } 
    }, 
    created: function() { 
     var self = this; 

     this.$http.get('/api/users/me', function(data) { 
      this.user = data; 
      self.active_club = data.active_club; 

     }) 

    } 


}).$mount('#app'); 

const club = new Vue(); 

//THIS NOT WORKING 
club.$on('active_club', function (id) { 

    alert(id) 
    this.active_club = id; 
}); 

錯誤:

Vue warn]: Error in watcher "club" (found in component )

vue_main.js:16924 Uncaught (in promise) ReferenceError: club is not defined

我已經嘗試了許多設置窗口,這是其中之一。如何使這個工作?

回答

0

$dispatch$broadcast已在Vue 2.0中棄用。

就你而言,你需要的是父組件和子組件之間的通信。當一個孩子$emit秒的情況下,家長可以通過提供模板標記本身就是一種方法,使用v-on:parentMethod()如下聽吧:

<child-component v-on:child-event="handlerMethod"></child-component> 

上述標記是父組件的模板內完成。父組件需要在其methods中有該handlerMethod

這裏是#2的樣本「親子溝通」的問題,其中有一個例子的jsfiddle也:Delete a Vue child component

您可以使用上面的回答作爲參考在您的應用程序來實現$emit

編輯:其他注意事項

我忘了提及你有三個層次結構的說明。在您的應用程序,您有以下層次:

父:vue_main

孩子1:HeaderElement

孩子1。1:ClubSelection

對於從ClubSelection向vue_main發送事件,您可以使用non parent-child communication method,也可以使用中間HeaderElement中繼事件。

這裏是事件中繼可以如何工作的:

  • 步驟1:ClubSelection發送$emit,其通過使用HeaderElement接收v-on
  • 第2步:HeaderElement中的handlerMethod執行this.$emit,可以使用另一個v-on通過主模板接收。

雖然上面的內容看起來有些複雜,但它比嚮應用程序中的每個組件傳播更有效率,因爲它通常在Angualr 1.x或其他框架中完成。

+0

如果你有兩個不相關的組件(不是父子),那麼你可以使用[Non-Parent-Child Communication](http://vuejs.org/guide/components.html#Non-Parent-Child-Communication)如文檔中所述。 – Mani

相關問題