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

Ale*_*lex 6 vue.js vue-router vue-component

我在呈现页面之前发送了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);
        },           
    }
};
Run Code Online (Sandbox Code Playgroud)

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

Phi*_*hil 8

尝试使用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);
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

更短

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'
        });
    }
};
Run Code Online (Sandbox Code Playgroud)

  • vuejs 组件的所有生命周期事件都是同步的。它们不能是异步的,至少在 v2.6 中是这样。 (5认同)