1

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.

1
  • 1
    <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, using import(), 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. Commented Feb 18, 2022 at 18:24

1 Answer 1

2

The router-view component will render the component based on its path :

<template>
   <router-view/>
</template>
<script>

export default defineComponent({

})
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.