2017-06-19 9 views
0

子孫の子コンポーネント間で通信する方法があります。 vue document。しかし、この方法を試してみると、うまくいきませんでした。以下は私のコードです。助けはありますか?イベント・バスとの親子でない親の通信は動作しません。

htmlページ:

<html> 
    <body> 
     <div id="app10"> 
      <component3 :id="id"></component3> 
      <component4 :id="id"></component4> 
     </div> 
    </body 

</html> 

ザ・JSスクリプト:私は何をしたいことはある

var bus = new Vue(); 
Vue.component('component3', { 
    template: ` 
    <div @click='change'> 
     {{id}} 
    </div> 
    `, 
    props: ['id'], 
    methods: { 
    change() { 
     console.log('??? component3 emit'); 
     bus.$emit('idSelected', 3); 
    } 
    }, 
    mounted() { 
    } 
}); 

Vue.component('component4', { 
    template: ` 
    <div> 
     {{id}} 
    </div> 
    `, 
    props: ['id'], 
}); 

var app10 = new Vue({ 
    el: '#app10', 
    data: function() { 
    return { 
     id: '?' 
    } 
    }, 
    mounted() { 
    bus.$on('idSelected', function(value) { 
     console.log('??? app10 click event value: ', value); 
     this.id = value; 
     console.log('??? this.id', this.id); 
    }); 
    }, 
    methods: { 
    } 
}); 

: '?疑問符' 私はcomponent3をクリックすると、そのテキストコンテンツから変更する必要があります3番にしかし、それは動作しません。親データの「id」が「3」に変更されても、子プロップの「id」はまったく変更されませんでした。どうして?

コンソール出力:

??? component3 emit 
??? app10 click event value: 3 
??? this.id 3 

答えて

1

これはスコープの問題です。次のようにmountedフックを調整します。

mounted() { 
    const self = this; // save pointer to current 'this' 
    bus.$on('idSelected', function(value) { 
     console.log('??? app10 click event value: ', value); 
     self.id = value; // use 'self' here 
     console.log('??? this.id', this.id); 
    }); 
    } 

それはあなたのイベントリスナーに「バス」に等しいので、それ以外の場合あなたは、現在の「これ」への参照を失います。あなたのリスナーの中でconsole.log(this === bus)を試してください(== true)。

+0

愚かな私は、この間違いをもう一度してください。ありがとう! – soarinblue

+0

ようこそ。 – wostex

1

thisの値は、あなたの匿名関数内のコード内で変化しています。 vueインスタンスのコンテキストを保持する代わりに、矢印関数を使用します。

var bus = new Vue(); 
 
Vue.component('component3', { 
 
    template: ` 
 
    <div @click='change'> 
 
     {{id}} 
 
    </div> 
 
    `, 
 
    props: ['id'], 
 
    methods: { 
 
    change() { 
 
     console.log('??? component3 emit'); 
 
     bus.$emit('idSelected', 3); 
 
    } 
 
    }, 
 
    mounted() { 
 
    } 
 
}); 
 

 
Vue.component('component4', { 
 
    template: ` 
 
    <div> 
 
     {{id}} 
 
    </div> 
 
    `, 
 
    props: ['id'], 
 
}); 
 

 
var app10 = new Vue({ 
 
    el: '#app10', 
 
    data: function() { 
 
    return { 
 
     id: '?' 
 
    } 
 
    }, 
 
    mounted() { 
 
    bus.$on('idSelected', (value) => { 
 
     console.log('??? app10 click event value: ', value); 
 
     this.id = value; 
 
     console.log('??? this.id', this.id); 
 
    }); 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script> 
 
<html> 
 
    <body> 
 
     <div id="app10"> 
 
      <component3 :id="id"></component3> 
 
      <component4 :id="id"></component4> 
 
     </div> 
 
    </body> 
 

 
</html>

関連する問題