selubamih
selubamih

Reputation: 83

Vue page cannot open after refreshing the page

I added the routes dynamically to the router and I can visit all pages with router-view. However, when I try to refresh the page I cannot visit the page again although the URL is the same. It is http://localhost:8081/me.

this.$router.addRoute("Main", {
              path: '/me',
              name: 'Me',
              component: () => import(`@/components/Me.vue`)
            });

As I said, I can normally visit the page "Me", but when I refresh it, I cannot see its content anymore with the warning:

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

I tried to create router with createWebHistory("/") after reading the cause of the error but nothing seems to change. I will appreciate any help.

Upvotes: 2

Views: 2615

Answers (1)

Harshal Patil
Harshal Patil

Reputation: 21030

There are two reasons why this would happen.

First serving SPA application from the server.

Make sure that your back-end is set to serve index.html file for all routes since back-end server is unaware of the routes set by client-side router. Something like express-history-api-fallback-middleware can help is using Node.js/Express.js.

Second problem is that of using addRoute.

As you described, the problem could be that Vue router is taking routing decision before your code in components/common/LeftMenu.vue is getting executed which is responsible for calling addRoute(). Ensure that this code is called before routing decision is being made. Best way would be to move this logic in top-level application component. And, if you can move that to top-level components, that means you can try to declare all routes while defining the router.

Why that should be done?

Using addRoute is not necessarily an anti-pattern but having to rely on addRoute is often code smell. You would really need it in extremely rare scenarios. Routing is a high-level architectural concern for your application and thus better to be declared upfront somewhere at top-level module even before application is getting initialized. Low level components should not attempt to manipulate routing data structure (violation of DIP principles).

One scenario where you might be tempted to use addRoute is taking decision after some data manipulation by the component with addition of some API call. That seems legitimate need but then to address that there are better ways. Considering using route guards (guards support async resolution too!) and prevent user from entering the view till the guard is resolved successfully.

Upvotes: 1

Related Questions