I'm a newbie to Vuejs and I'm wondering how I can load the component to App.vue depending on the route visited.
In my router -> index.js I have:
import { createRouter, createWebHistory} from 'vue-router'
import Events from '../views/Events.vue'
const routes = [
{
path: '/',
name: 'events',
component: Events
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
In my App.vue I have a template that I want to use for the entire website, so I thought to load the template here instead of loading it into each component.
My template has 1 box in the center of the screen, so the content changes depending on which route the user goes to.
Instead of calling the component content from the routes file, is there a better way to load it dynamically into App.vue depending on the route visited?
I could hard code it in App.vue with something like:
<template>
<Events />
</template>
<script>
import Events from './views/Events.vue'
export default defineComponent({
components: {
Events
},
</script>
But that won't solve my problem about the Events component being loaded dynamically depending on which route is visited. Is there a way to access the underlying component with something like this.$route to load the component instead of hard coding it.
<router-view>is precisely that. Nothing more, nothing less. But rather than specifying the components in the App's template, you specify them in the routes array. Additionally, you can lazy load them, usingimport(), so they only get loaded when they're actually accessed. A very important note is that you can have nested<router-view>s, for child pages. They can go for as many levels you want, although you'll rarely use even the second level, nevermind a third one.