Home > Back-end >  vuejs loading component dynamically depending on route component
vuejs loading component dynamically depending on route component

Time:02-19

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.

CodePudding user response:

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

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

export default defineComponent({

})
</script>
  • Related