skip to Main Content

Why scoped slots aren’t working in vue js 3 ?
I’m returning an object with v-for loop but the specialty field isn’t visualized. I think I have an error. And the console is empty

I’m expecting to return an array with v-for loop in vue js 3

// Child component
<tr v-for="person in crew" :key="person.id">
    <slot name="speciality-body" :crew="person.speciality"></slot>
    <td>{{person.tab}}</td>
    <td>{{person.fullname}}</td>
  </tr>
// Parent component
<CrewComponent :crew="crew.crew">
      <template #speciality-body="{speciality}">
        <td>{{speciality}}</td>
      </template>
    </CrewComponent>

// data. parent component
      crew: {
        crew: [
          {
            id: '1',
            speciality: 'fds'
          },
          {
            id: '2',
            speciality: 'fgh'
          }, ...

2

Answers


  1. You should place the element directly within the element, and not as a direct child of the slot.
    Here’s the corrected version of the child component code:

    <template>
        <tr v-for="person in crew" :key="person.id">
        <slot name="speciality-body" :crew="person.speciality">
            <td>{{ person.speciality }}</td>
        </slot>
        <td>{{ person.tab }}</td>
        <td>{{ person.fullname }}</td>
        </tr>
    </template>
    

    Here’s the corrected version of the parent component code:

    <CrewComponent :crew="crew.crew">
        <template #speciality-body="{ crew: speciality }">
        <td>{{ speciality }}</td>
        </template>
    </CrewComponent>
    
    Login or Signup to reply.
  2. There appears to be a typo in the property name. In the child component, you’re binding the person.speciality to the crew property, but then in the parent component, you’re trying to destructure it using the name speciality. This discrepancy in the property name would cause the value to be undefined.

    You should change the child component’s slot binding to match the name you’re using in the parent component, like this:

    Child Component:

    <tr v-for="person in crew" :key="person.id">
      <slot name="speciality-body" :speciality="person.speciality"></slot>
      <td>{{person.tab}}</td>
      <td>{{person.fullname}}</td>
    </tr>
    

    Parent Component and Data would remain the same. By making this change, the scoped slot should work correctly, and the speciality field should be visualized as expected.

    If you still encounter issues, make sure that the rest of your code is consistent, and there’s no other typographical or logical errors elsewhere in the components. Also, make sure that the data is correctly passed to the child component and that the crew prop is correctly defined in the child component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search