我在渲染页面之前发送了 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
方法之前。如何正确渲染我的组件?
原文由 Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议
正如评论中提到的,第一个 async/await 解决方案有点误导,因为所有生命周期方法都是 synchronous 。这是可行的,因为代码被转换为内部带有 IIFE 的同步函数。
下面我添加了一些最近的片段。
旧答案
用 async/await 试试。我删除了
beforeRouteEnter
,axios.spread
并添加了create
。更短
更新的答案
您可以在生命周期方法中使用异步函数。
Vue 3和
setup()
在 Vue 3 中,您可以使用
async setup()
。如果你使用它,你必须用Suspense
包装你的组件。警告!这个 API 目前是 实验性 的 https://vuejs.org/guide/built-ins/suspense.html#suspense= 。