8

I need to create routes dynamically within a Vue application. I have created a basic component on this code sandbox link.

The issue that I am encountering is that on first load the home page is returning a 404, even though the route has been added within the created() lifecycle of the app. I understand that the issue with this is that the navigation is triggered before app creation and therefore that is why when navigating on the app, the navigation resolves itself.

On my higher scale application, the error returned is (not showing on Sandbox because the Not Found page is defined):

[Vue Router warn]: No match found for location with path "/"

Please do not provide solutions that include adding the routes upon initialising the VueRouter because I specifically need to add them in the created() lifecycle of the app since the data I will be receiving will be from an API and I would need to handle it there.

I have tried using navigation guards but I have not managed to solve the issue as of yet.

Let me know what I am doing wrong and how I can go around solving this issue please. Any help is greatly appreciated.

Thanks in advance.

Good day to you all. :)

Senate No. 7
  • 133
  • 1
  • 2
  • 8

4 Answers4

4

You need to trigger a new navigation after the route is added: https://next.router.vuejs.org/guide/advanced/dynamic-routing.html#adding-routes

Posva
  • 1,104
  • 9
  • 15
2

i have met this problem too when i try to generate dynamic routes ,what i found is when enter a route what i not register yet will go to this error , so you need to register a 404 page to wait our routes registered register a 404 route

hope to help u

suky li
  • 21
  • 2
-1

In your /router/index.js, please add the following code after the declaration of const router:

router.addRoute('admin', { path: 'settings', component: AdminSettings })

Here you can just replace 'admin' with your own parent path;
set 'settings' as the child path;
and the component as the child component that you want.

Refresh your page then you can see the component AdminSettings with the URL like: localhost:5713/admin/settings .

Hope this helps. https://router.vuejs.org/guide/advanced/dynamic-routing.html#adding-nested-routes

generalzyq
  • 303
  • 3
  • 11
-2

I think you need store full path in local storage in router guard when page change, then get this path to redirect when app created.

Tenn Chio
  • 1
  • 2