Blog>
Snippets

Component Slot Content and Virtual DOM Rendering

Illustrate the use of slots in Vue.js and how they interact with the Virtual DOM when distributing content among components.
<div id="app">
  <custom-component>
    <template v-slot:default>
      <p>This is default slot content.</p>
    </template>
    <template v-slot:header>
      <h1>This is a header slot content.</h1>
    </template>
  </custom-component>
</div>
HTML structure using Vue.js slots. The parent component (<custom-component>) defines where the distributed content will be placed by using the <slot> element with a name (default and header in this case).
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.10/dist/vue.js"></script>
<script>
  // Registering custom-component
  Vue.component('custom-component', {
    template: `
      <div>
        <header>
          <slot name="header">Default Header</slot>
        </header>
        <main>
          <slot>Default Content</slot>
        </main>
      </div>
    `
  });

  // Creating a new Vue instance to mount our app
  new Vue({
    el: '#app'
  });
</script>
The Vue component is defined with named slots for the header and default content. If the slots are not provided by the parent, default values are rendered. A new Vue instance is created and linked to the HTML element with id 'app'. Vue uses the Virtual DOM to render components efficiently.
<style>
  custom-component > header {
    background-color: #f8f8f8;
    padding: 20px;
    text-align: center;
  }

  custom-component > main {
    margin: 20px;
    padding: 20px;
    border: 1px solid #ddd;
  }
</style>
CSS styles for custom-component's children elements (<header> and <main>). These styles will apply to the slot content when it's rendered inside these elements.