gpt4 book ai didi

vuejs2 - 如何将数据从 Vue 实例传递到组件

转载 作者:行者123 更新时间:2023-12-01 15:35:26 25 4
gpt4 key购买 nike

首先,我必须说我已经在这上面花了几个小时,所以如果我忽略了一些非常简单的事情,我深表歉意。

我试图让一个组件通过根 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 调用的数据重新加载选择输入。

这是 html 片段:

<fig-model-dropdown v-bind:make="make" make="{{ $value->make_id }}" model="{{ $value->model_id }}"></fig-model-dropdown>

这是模型组件:

<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?

最佳答案

这似乎是因为您的 this 没有指向 fetchModelsByMake 方法中的正确范围。 this 的范围将在 '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); }, 函数(错误){ //处理错误 } );

你也可以看看我类似的回答here .

关于vuejs2 - 如何将数据从 Vue 实例传递到组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41092305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com