Blog>
Snippets

Scoped Slot with Data

Shows how to pass data from a child component to a parent using a scoped slot with a specific name.
<template>
  <div>
    <!-- Parent component template -->
    <child-component>
      <!-- Scoped slot with the name 'user-details' -->
      <template v-slot:user-details="slotProps">
        <!-- Accessing the child's data via the slotProps object -->
        <p>Name: {{ slotProps.name }}</p>
        <p>Age: {{ slotProps.age }}</p>
      </template>
    </child-component>
  </div>
</template>
This is the parent component's template. It uses a scoped slot named 'user-details' to define how to render the data passed from the child component.
<script>
  // Import Vue and child-component in the parent component
  import Vue from 'vue';
  import ChildComponent from './ChildComponent.vue';

  export default {
    components: {
      ChildComponent
    }
  }
</script>
The parent component includes the child component using Vue's import syntax and registers it in the components object.
<style>
  /* CSS styles for parent and child components if needed */
</style>
This section includes any CSS styles that might be necessary for the parent or child components.
<template>
  <div>
    <!-- Child component template -->
    <!-- Defining the scoped slot and passing data to the slot -->
    <slot name="user-details" :name="userName" :age="userAge"></slot>
  </div>
</template>
This is the child component's template. It defines a slot with the name 'user-details' and binds data (userName and userAge) to the slot.
<script>
  export default {
    data() {
      return {
        // Child component's data properties
        userName: 'John Doe',
        userAge: 30
      };
    }
  };
</script>
The child component's script block defines its data properties, such as userName and userAge, which will be passed to the parent component.