所以我在Vue上開發應用程序。我在組件之間發送和接收數據時遇到問題。已經嘗試過$dispatch/$broadcast
,$emit/$on
,但現在仍在工作。我想將選定的active_club
從ClubSelection.vue
發送到vue_main.js
。我的應用程序的Vue 2 - 組件之間的通信(發送和接收數據)
Vue version: 2.0.3
結構:
- vue_main - 主要VUE文件
- HeaderElement.vue(孩子vue_main的)
- ClubSelection.vue(孩子HeaderElement)
- HeaderElement.vue(孩子vue_main的)
需要從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
我已經嘗試了許多設置窗口,這是其中之一。如何使這個工作?
如果你有兩個不相關的組件(不是父子),那麼你可以使用[Non-Parent-Child Communication](http://vuejs.org/guide/components.html#Non-Parent-Child-Communication)如文檔中所述。 – Mani