我在渲染页面之前发送了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);
},
}
};
问题是渲染发生在setProfile
和setPhotos
方法之前。如何正确渲染我的组件?
尝试使用async / await。我已经删除beforeRouteEnter
,axios.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] 删除。
我来说两句