Blog>
Snippets

Dynamic Component with Named Slots

Shows how to use the <component> tag with named slots to dynamically switch between different components passed as slot content.
<template id="header-component">
  <header>
    <slot name="logo"></slot>
    <nav>
      <slot name="navigation"></slot>
    </nav>
  </header>
</template>

<template id="footer-component">
  <footer>
    <slot name="info"></slot>
  </footer>
</template>
HTML templates for header and footer components with named slots.
<div id="app">
  <component is="currentComponent">
    <!-- Named slot for the logo -->
    <img slot="logo" src="logo.png" alt="Logo">

    <!-- Named slot for navigation -->
    <ul slot="navigation">
      <li>Home</li>
      <li>About</li>
      <li>Contact</li>
    </ul>

    <!-- Named slot for footer info -->
    <p slot="info">&copy; 2023 Company Name</p>
  </component>
</div>
HTML structure where the <component> tag is used to dynamically switch between the header and footer components with named slot content.
const app = new Vue({
  el: '#app',
  data: {
    currentComponent: 'header-component'
  }
});
Vue instance binding the #app element and setting the initial component to 'header-component'.
header, footer {
  background-color: #e0e0e0;
  padding: 1rem;
  text-align: center;
}

nav ul {
  list-style-type: none;
  padding: 0;
}

nav li {
  display: inline;
  margin-right: 1rem;
}
CSS styles for the header, footer, and navigation elements.