2017-06-17 28 views
0

我有分量,里面我做冒落:不能从一个孩子发出另一个

methods: { 
    sendClick(e) 
    { 
     bus.$emit('codechange', this.mycode); 
     console.log(this.selectedLanguage); 
     this.$parent.sendCode(); 
     this.$parent.changeView(); 
    } 

} 

在父组件我hadling数据:

var app = new Vue({ 
    el: '#app', 
    data: { 
    currentView: 'past-form', 
    mycode: '' 
    }, 
    methods: 
    { 
    changeView() 
    { 
     console.log(this.mycode); 
    }, 

    sendCode() 
    { 
     console.log("Code is sended to server"); 
     this.currentView = 'view-form'; 
     bus.$emit('codechange', this.mycode); 
    } 

    }, 

    created() 
    {   
    bus.$on('codechange', function(mycode){ 
    console.log("test"); // this works 
    this.mycode = mycode; // this works 
    }.bind(this)); 

    } 

}) 

处理在父母工作精细。但点击sendCode()我想发送数据到第三个组件。第三个组件代码:

Vue.component('view-form', { 
    template: ` 
     <div class="ViewCodeContainer"> 
      <div class="ViewCode">my code here</div> 
      <code> {{mycode}} </code> 
      <div class="ViewCodeMenu">my menu here</div> 
     </div>`, 
     data() { 
      return { 
       mycode: '' 
      } 
     }, 
    created() 
     {  
      bus.$on('codechange', function(mycode){ 
      console.log("hererere"); 
       console.log(mycode); 
      this.mycode = mycode; 
      }.bind(this)); 
      console.log("test"); 
     } 
}) 

但是,处理代码不起作用。块console.log("hererere");未执行。我做错了什么?

+0

看起来像“view-form”组件根本就没有创建。确保它出现在你的模板中。或者console.log在listener之前的'created'钩子中。否则它应该工作:https://jsfiddle.net/wostex/63t082p2/74/ – wostex

+0

它的创建,因为我可以切换到它。如果我是硬编码'我的代码'它,我可以看到它 –

+0

您是否正在使用'is'设置为'currentView'的动态组件? – Bert

回答

1

@Wostex在这种情况下是正确的。本质上,当事件发出时,您的view-form组件不存在。直到您更改视图,您在事件处理程序中执行的视图才会存在。所以没有办法让它接收事件,因为你的处理程序不存在。

如果您的动态组件是父级的子级,只需将代码作为属性传递即可。

<component :is="currentView" :mycode="mycode"></component> 

并更新您的view-form组件。

Vue.component('view-form', { 
    props:["mycode"], 
    template: ` 
    <div class="ViewCodeContainer"> 
     <div class="ViewCode">my code here</div> 
     <code> {{code}} </code> 
     <div class="ViewCodeMenu">my menu here</div> 
    </div>`, 
    data() { 
    return { 
     code: this.mycode 
    } 
    } 
}) 

这是一个工作example

相关问题