首先,我必须说我花了好几个小时,所以如果我忽略了一些简单的事情,那么我就道歉了。
我试图让一个组件通过根Vue实例与另一个组件通信。到目前为止,我已经设法让MakeComponent向根实例发送消息,如下所示:
const eventHub = new Vue() // Single event hub
// Distribute to components using global mixin
Vue.mixin({
data: function () {
return {
eventHub: eventHub
}
}
});
Vue.component('fig-make-dropdown', require('./components/FigMakeDropdown.vue'));
Vue.component('fig-model-dropdown', require('./components/FigModelDropdown.vue'));
/**
* Next, we will create a fresh Vue application instance and attach it to
* the body of the page. From here, you may begin adding components to
* the application, or feel free to tweak this setup for your needs.
*/
const app = new Vue({
el: '#app',
data: function() {
return {
makes: {},
make: '',
componentMake: ''
};
},
mounted() {
this.eventHub.$on('broadcast_make', data => {
// do your thing
console.log('parent', data);
this.make = data;
});
}
});
this.eventHub。$ on成功输出传入的make值。我想要做的是将它发送到ModelComponent,以便它可以使用该make变量重新加载来自ajax调用的数据的select输入。 p>
这是html代码段:
<fig-model-dropdown v-bind:make="make" make="{{ $value->make_id }}" model="{{ $value->model_id }}"></fig-model-dropdown>
这是ModelComponent:
<template>
<div>
<label for="make_model_id">Model</label>
<select id="make_model_id" name="make_model_id" class="form-control" v-model="componentModel">
<option value=""></option>
<option :value="model.id" v-for="model in models">{{ model.name }}</option>
</select>
</div>
</template>
<script>
export default {
props: {
'make':'',
'model': {
'default': ''
}
},
data: function() {
return {
componentMake: '',
componentModel: '',
models: {}
};
},
created: function() {
console.log('fig-model-dropdown Component ready.');
if(this.make) {
console.log('MAKE', this.make);
this.componentMake = this.make;
this.fetchModelsByMake();
}
if(this.model) {
this.componentModel = this.model;
}
},
methods: {
fetchModelsByMake: function() {
this.$http.get('/api/make/models/' + this.make ).then(
function (models) {
this.models = models.body;
// console.log('MODEL', this.model);
}, function (error) {
// handle error
}
);
}
}
}
</script>
使用此代码,我没有错误,但没有明显指示ModelComponent已收到它。我现在如何将make传递给ModelComponent并重建select?
答案 0 :(得分:1)
似乎发生了这种情况,因为this
未指向fetchModelsByMake
方法中的正确范围。这个范围会在'this。$ http'调用中发生变化,所以你只需要执行以下操作:
fetchModelsByMake: function() {
var self = this
this.$http.get('/api/make/models/' + this.make ).then(
function (models) {
self.models = models.body;
// console.log('MODEL',this.model); },function(error){ //处理错误 } );
您还可以查看我的类似答案here。