简体   繁体   English

Vue.js - 来自AJAX Call的全局数据

[英]Vue.js - Global Data from AJAX Call

I'm giving Vue.js a try and so far I'm loving it because it's much simpler than angular. 我正在尝试Vue.js ,到目前为止,我很喜欢它,因为它比角度更简单。 I'm currently using vue-router and vue-resource in my single page app, which connects to an API on the back end. 我目前在我的单页应用程序中使用vue-routervue-resource ,后者连接到后端的API。 I think I've got things mostly working with a the primary app.js , which loads vue-router and vue-resource, and several separate components for each route. 我认为我的主要工作是主要的app.js ,它加载了vue-router和vue-resource,以及每个路由的几个独立组件。

Here's my question: How do I use props to pass global data to the child components when the data is fetched using an asynchronous AJAX call? 这是我的问题:当使用异步AJAX调用获取数据时,如何使用props将全局数据传递给子组件? For example, the list of users can be used in just about any child component, so I would like the primary app.js to fetch the list of users and then allow each child component to have access to that list of users. 例如,用户列表几乎可以在任何子组件中使用,因此我希望主app.js获取用户列表,然后允许每个子组件访问该用户列表。 The reason I would like to have the app.js fetch the list of users is so I only have to make one AJAX call for the entire app. 我想让app.js获取用户列表的原因是我只需要为整个应用程序进行一次AJAX调用。 Is there something else I should be considering? 还有什么我应该考虑的吗?

When I use the props in the child components right now, I only get the empty array that the users variable was initialized as, not the data that gets fetched after the AJAX call. 当我现在使用子组件中的props时,我只得到users变量初始化的空数组,而不是AJAX调用后获取的数据。 Here is some sample code: 以下是一些示例代码:

Simplified App.js 简化的App.js

var Vue = require('vue');

var VueRouter = require('vue-router')
Vue.use(VueRouter);
var router = new VueRouter({
    // Options
});

router.map({
    '*': {
        component: {
            template: '<p>Not found!</p>'
        }
    },
    '/' : require('./components/dashboard.js'),
});

Vue.use(require('vue-resource'));

var App = Vue.extend({
    ready: function() {
        this.fetchUsers();
    },

    data: function() {
        return {
            users: [],
        };
    },

    methods: {
        fetchUsers: function() {
            this.$http.get('/api/v1/users/list', function(data, status, response) {
                this.users = data;
            }).error(function (data, status, request) {
                // handle error
            });
        }
    }
});

router.start(App, '#app')

Simplified app.html 简化的app.html

<div id="app" v-cloak>
    <router-view users = "{{ users }}">
    </router-view>
</div>

Simplified dashboard.js 简化的dashboard.js

module.exports = {
    component: {
        ready: function() {
            console.log(this.users);
        },

        props: ['users'],
    },
};

When dashboard.js gets run, it prints an empty array to the console because that's what app.js initializes the users variable as. dashboard.js运行时,它会向控制台输出一个空数组,因为app.jsusers变量初始化为。 How can I allow dashboard.js to have access to the users variable from app.js ? 如何允许dashboard.js访问app.jsusers变量? Thanks in advance for your help! 在此先感谢您的帮助!

ps I don't want to use the inherit: true option because I don't want ALL the app.js variables to be made available in the child components. ps我不想使用inherit: true选项,因为我不希望所有app.js变量在子组件中可用。

I believe this is actually working and you are being misled by the asynchronous behavior of $http . 我相信这实际上是有效的,你被$http的异步行为误导了。 Because your $http call does not complete immediately, your console.log is executing before the $http call is complete. 因为你的$http调用不会立即完成,你console.log被执行前的$http调用完成。

Try putting a watch on the component against users and put a console.log in that handler. 尝试针对users watch组件,并在该处理程序中放置console.log

Like this: 像这样:

module.exports = {
    component: {
        ready: function() {
            console.log(this.users);
        },

        props: ['users'],

        watch: {
            users: {
                handler: function (newValue, oldValue) {
                    console.log("users is now", this.users);
                },
                deep: true
            }
        }
    }
};

In the new version of Vue 1.0.0+ you can simply do the following, users inside your component is automatically updated: 在新版本的Vue 1.0.0+中,您可以简单地执行以下操作,组件内的用户会自动更新:

<div id="app" v-cloak>
    <router-view :users="users"></router-view>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM