【发布时间】:2018-12-03 17:41:41
【问题描述】:
我是 Vue.js 生态系统的新手,需要一些建议。
我通过axios 包制作GET request。我想显示整页的预加载器,直到所有数据都来了。我认为这个任务并不新鲜,但我想了解在 Vue.js 中这些事情通常是如何完成的。
对于预加载器,我创建了新组件。我有点困惑。如何从其他组件调用该组件并使其在特定时间可见。
【问题讨论】:
标签: javascript vue.js vuejs2 axios
我是 Vue.js 生态系统的新手,需要一些建议。
我通过axios 包制作GET request。我想显示整页的预加载器,直到所有数据都来了。我认为这个任务并不新鲜,但我想了解在 Vue.js 中这些事情通常是如何完成的。
对于预加载器,我创建了新组件。我有点困惑。如何从其他组件调用该组件并使其在特定时间可见。
【问题讨论】:
标签: javascript vue.js vuejs2 axios
您可以在 axios all 和 spread 之前显示您的预加载用户界面(以提出您的所有请求)和 then 以隐藏该预加载用户界面。示例如下:
// show preload ui
showSpinnerAnimation();
// Requests will be executed in parallel...
axios.all([
axios.get('https://somelink');
axios.get('https://someotherlink')
])
.then(axios.spread(function (somelinkResponse, someotherlinkResponse) {
//... but this callback will be executed only when both requests are complete.
console.log('somelinkResponse', somelinkResponse.data);
console.log('someotherlinkResponse', someotherlinkResponse.data);
// hide preload ui
hideSpinnerAnimation();
}));
【讨论】:
Axios 的工作方式与 ajax 不同。可以说是javascript ajax函数的进阶版。
axios小例子:
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
【讨论】: