darthvader
darthvader

Reputation: 1

Can we pass templates existing in a different file to slots in a component

I have ComponentA which has slots content and actions and it looks like this

<template>
  <div>
    <slot name="content">
      // initial state content
    </slot>
    <slot name="actions">
      // initial state actions
    </slot>
  </div>
</template>

In my MainComponent.vue, I am using ComponentA like this

<template>
  <div>
    <component-A>
       <template #content>
         // components go here
       </template>
       <template #actions>
        // actions go here
       </template>
    </component-A>
  </div>
</template>

How can I put ComponentX into ComponentA instead of establishing templates inside of ComponentA in my MainComponent and what should ComponentX look like?

What i tried so far is this in my MainComponent.vue, I am using ComponentA like this

<template>
  <div>
    <component-A>
       <component-X>
    </component-A>
  </div>
</template>

And my ComponentX looks like this

<template>
  <div>
    <slot name="content">
      <div class="d-flex flex-column">
        <v-select
           label="test"
           :items="[]"
      </div>
    </slot>
    <slot name="actions">
      <v-row>
        <v-spacer />
        <v-btn
          text="OK"
          @click="doSomething"
        />
      </v-row>
    </slot>
  </div>
</template>

My Expectation is that any component put into ComponentA with matching slots should be picked up by it and rendered accordingly.

Upvotes: 0

Views: 512

Answers (1)

justalittleheat
justalittleheat

Reputation: 403

Unfortunately components and slots do not work they way you are thinking. What you could do that may be a similar is add a <slot> without a name in Component A around your named slots.

Component A

</template> 
  <div>
    <slot>
        <slot name="content">
          // initial state content
        </slot>
        <slot name="actions">
          // initial state actions
        </slot>
    </slot>
  </div>
</template>

This will allow you to completely override both the content and actions slots in Component A with Component X. Since you don't specify a slot name for Component X to use it will take the place of default slot in Component A.

MainComponent.vue

<template>
  <div>
    <component-A>
       <component-X />
    </component-A>
  </div>
</template>

Upvotes: 1

Related Questions