2016-10-27 48 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

相关问题