How to fetch data in router index.ts?

问题描述 投票:0回答:1

因此,我有一个问题,即路线已经太晚了,并且存在,但是当我重新加载页面时,它们不会显示,所以我猜测它们的加载太晚了。 I have the following code in the index.ts of the router:

fetch('http://localhost:8000/api/test/all').then((response) => response.json())
.then((data) => { 
  if (data) {
    for (let route of data)  {
      router.addRoute({path: '/' + route.name, name: route.name, component: () => import('../views/TestView.vue')})
    }
  };
});

Is there some sort of lifecycle hook, or can I make it somehow to wait for the result before navigating to the page? 我尝试了Beforerouteenter,但它没有起作用。 我在app.vue

中尝试的。

router.beforeEach((to, from, next) => { fetch('http://localhost:8000/api/test/all').then((response) => response.json()) .then((data) => { if (data) { for (let route of data) { router.addRoute({path: '/' + route.name, name: route.name, component: () => import('./views/TestView.vue')}) } next() }; }); })

但是当我刷新 /xy时,我会得到一个空白网站,因为它找不到 /xy

vue.js
1个回答
0
投票

await addDynamicRoutes(); app.use(router) app.mount(...);

替代方法是在路由器钩中处理此操作,这是在
文档中介绍的:

let dynamicRoutesAdded; router.beforeEach(async (to, from) => { if (dynamicRoutesAdded) return; await addDynamicRoutes(); dynamicRoutesAdded = true; return to.fullPath; });

next

由于路由器挂钩支撑承诺而被弃用。

	

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.