在mounted函数中,我创建了一个动作,它将Rest Api中的数据fetch到vuejs组件中的表中
mounted() {
UserService.getProjects().then(
(response) => {
this.isProject = true;
this.projects = response.data;
},
(error) => {
this.isProject = false;
}
);
}但是,当我在菜单上点击到这个页面的路径时,我在一秒钟内被重定向到这个页面,但是我的数据仍然在加载,并且在开始时我有一个空表……,如何获取数据然后重定向到这个页面?谢谢你的帮助
ps。我使用router-link导航到另一个页面
发布于 2021-02-15 01:32:35
要回答你的确切问题,你可以看看Navigation Guards。
在您的路由器中,执行类似操作
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
UserService.getProjects().then(
(response) => {
// update store or some state
next()
},
(error) => {
// update store or some state
next(false); //cancel or handle the error
}
);
}
}
]
})但是,您可能不希望在加载数据之前延迟路由转换。相反,您希望在数据就绪之前显示加载状态。因此,您只需在您的模板和现有的mounted函数中处理它,就像您所做的那样。
通过阻塞导航,您必须决定在数据加载失败时该如何处理
发布于 2021-02-15 01:16:12
您可以尝试在挂载的钩子上使用async和await。
async mounted() {
await UserService.getProjects().then(
(response) => {
this.isProject = true;
this.projects = response.data;
},
(error) => {
this.isProject = false;
}
);
}或者,您也可以使用Promise。
async mounted() {
await Promise.all(
UserService.getProjects().then(
(response) => {
this.isProject = true;
this.projects = response.data;
},
(error) => {
this.isProject = false;
}
);)
}https://stackoverflow.com/questions/66197873
复制相似问题