I add a route dynamically and it works but I get the warning below.
"No match found for location with path "/test".
Code Sandbox demo url. https://codesandbox.io/p/github/eguvenc/routertest/v1.x
main.js
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import TestView from './views/TestView.vue'
const app = createApp(App)
app.use(router)
router.addRoute(
{
path: '/test', component: TestView
}
)
router.beforeEach(async (to, from, next) => {
console.error(to);
next();
if (to.matched.length == 0) {
// router.push({ path: to.fullPath })
// we could also use this.$route or useRoute()
router.replace(to.fullPath)
}
})
app.mount('#app')
App.vue
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
<a href="/test"><b>Test Dynmaic Route</b></a>
</nav>
The problem is the navigation in Vue router starts at a different time from the rest of the application and can end at different time too, this is the reason for router.isReady
method to exist.
It specifically starts at the time when router plugin is registered, not when the app is mounted. If initial navigation relies on dynamic routes, they should be registered before the plugin, so should router hooks:
router.addRoute(...)
router.beforeEach(...)
app.use(router)
The problem could be avoided by moving all router-related logic to router module, so there would be no possibility for race conditions in main module.