在渲染组件之前从api获取数据

亚历克斯

我在渲染页面之前发送了2个api请求:

const Profile = {
    template: '#profile',
    attributes: null,
    photos: [],
    data: function () {
        return {attributes: Profile.attributes, photos: Profile.photos};
    },
    beforeRouteEnter: function (to, from, next) {
        function getProfile() {
            return axios.get('user/get-profile?access-token=1', {responseType: 'json'});
        }
        function getPhotos() {
            return axios.get('photos?access-token=1', {responseType: 'json'});
        }

        axios.all([getProfile(), getPhotos()])
            .then(axios.spread(function (profile, photos ) {
                console.log(profile, photos );
                next(vm => {
                    vm.setProfile(profile);
                    vm.setPhotos(photos);
                })
            }));
    },
    methods: {
        setProfile: function (response) {
            Profile.attributes = response.data;
            console.log(Profile.attributes);
        },
        setPhotos: function (response) {
            Profile.photos = response.data;
            console.log(response);
        },           
    }
};

问题是渲染发生在setProfilesetPhotos方法之前如何正确渲染我的组件?

菲尔

尝试使用async / await。我已经删除beforeRouteEnteraxios.spread并添加create发出所有请求后,将加载组件。

const Profile = {
    template: '#profile',
    attributes: null,
    photos: [],
    data() {
        return {
            attributes: null,
            photos: null
        };
    },
    async created() {
        const getProfile = await axios.get('user/get-profile?access-token=1', {
            responseType: 'json'
        });
        const getPhotos = await axios.get('photos?access-token=1', {
            responseType: 'json'
        });

        this.setProfile(profile);
        this.setPhotos(photos);
    },
    methods: {
        setProfile(response) {
            this.attributes = response.data;
            console.log(this.attributes);
        },
        setPhotos(response) {
            this.photos = response.data;
            console.log(response);
        }
    }
};

更短

const Profile = {
    template: '#profile',
    attributes: null,
    photos: [],
    data() {
        return {
            attributes: null,
            photos: null
        };
    },
    async created() {
        this.attributes = await axios.get('user/get-profile?access-token=1', {
            responseType: 'json'
        });
        this.photo = await axios.get('photos?access-token=1', {
            responseType: 'json'
        });
    }
};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章