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)
问题是渲染之前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);
}
}
};
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)
| 归档时间: |
|
| 查看次数: |
13894 次 |
| 最近记录: |