如何将数据从 Vue 实例传递到组件 [英] How to pass data from Vue instance to component

查看:39
本文介绍了如何将数据从 Vue 实例传递到组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我必须说我在这上面花了几个小时,所以如果我忽略了一些非常简单的事情,那么我要道歉.

First I must say I have spent hours on this so if I have overlooked something stupidly simple then I do apologise.

我正在尝试通过根 Vue 实例让一个组件与另一个组件通信.到目前为止,我已经设法让 MakeComponent 向根实例发送消息,如下所示:

I am trying to get one component to talk to another via the root Vue instance. So far I have managed to get the MakeComponent to send a message to the root instance as shown below:

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 输入的数据.

这是 html 片段:

The this.eventHub.$on successfully outputs the make value passed in. What I want to do is send that to the ModelComponent so that it can reload the select input with data from an ajax call using that make variable.

Here is the html snippet:

这是模型组件:

And here is the ModelComponent:

</模板><脚本>导出默认{道具: {'制作':'','模型': {'默认': ''}},数据:函数(){返回 {组件制作:'',组件模型:'',楷模: {}};},创建:函数(){console.log('fig-model-dropdown 组件准备好.');如果(this.make){console.log('MAKE', this.make);this.componentMake = this.make;this.fetchModelsByMake();}如果(这个.模型){this.componentModel = this.model;}},方法: {fetchModelsByMake:函数(){this.$http.get('/api/make/models/' + this.make ).then(功能(模型){this.models = 模型体;//console.log('MODEL', this.model);}, 函数(错误){//处理错误});}}}

<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 并重建选择?

With this code I get no errors but no apparent indication that the ModelComponent has received it. How do i now pass the make into the ModelComponent and rebuild the select?

推荐答案

这似乎是因为您的 this 没有指向 fetchModelsByMake 方法中的正确范围.this 的范围将在 'this.$http' 调用中更改,因此您只需执行以下操作:

It seems this is happening because your this is not pointing to correct scope in fetchModelsByMake method. scope of this will change inside a 'this.$http' call, so you just have to do something like following:

        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);}, 函数(错误){//处理错误});

// console.log('MODEL', this.model); }, function (error) { // handle error } );

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

You can also have a look at my similar answer here.

这篇关于如何将数据从 Vue 实例传递到组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆