2017-06-19 143 views
0

在vue js文檔中,有一種方法可以在非父子組件之間進行通信。 vue document。但是當我嘗試這種方法時,它不起作用。以下是我的代碼。有什麼幫助嗎?Vue js與事件總線的父子通信不起作用

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>