所以我在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