Blog>
Snippets

Integrating Fragments with Vue Router

Show how to use fragments with Vue Router's route components to render multiple components associated with a route.
// Define the components
const HeaderComponent = {
  template: '<div>This is the header component</div>'
};
const MainComponent = {
  template: '<div>This is the main component</div>'
};
const FooterComponent = {
  template: '<div>This is the footer component</div>'
};
Here we're defining three simple Vue components that we'll use to demonstrate fragments within a route.
// Set up the router
const router = new VueRouter({
  routes: [
    {
      path: '/page',
      components: {
        header: HeaderComponent,
        default: MainComponent,
        footer: FooterComponent
      }
    }
  ]
});
Next, we create a VueRouter instance, defining a route that uses named views, corresponding to our header, main, and footer components. This allows us to render multiple components when this route is matched.
new Vue({
  router
}).$mount('#app');
We then create a new Vue instance, passing our router configuration to it. This instance is then mounted to an HTML element with the id 'app'.
// App.vue or your main Vue file
<template>
  <div>
    <router-view name="header"></router-view>
    <router-view></router-view>
    <router-view name="footer"></router-view>
  </div>
</template>
In your main Vue file (e.g., App.vue), we use the 'router-view' elements to declare spots where the respective components will be rendered. 'name' attributes are used to specify which named view should be rendered in each 'router-view'.