Praveen Puglia
Praveen Puglia

Reputation: 5631

Conditional scoped slot templates in vue

Can I not do something like this?

<template v-if="options.columns">
  one thing...
</template>
<template v-else slot-scope="scope">
  something else. scope doesn't work here. :(
</template>

When I try to do this, scope becomes undefined. The moment I remove v-if, else and use scope it works as expected.

Upvotes: 2

Views: 14520

Answers (3)

RomainV
RomainV

Reputation: 293

In Vue.js component you cannot have more than one template tag.

Why not using 'is' property for dynamic component ?

<template>
   <div :is='my-component'></div>
</template>

So you can load a component dynamicaly.

https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components

Upvotes: -1

user17408941
user17408941

Reputation:

The solution is a workaround:

Create 2 different SFC for each possible use case and do conditional rendering.

Vuetify example:

// App.vue
<div>
  <ListMD v-if="this.$vuetify.breakpoint.name === 'md'" />
  <ListXS v-if="this.$vuetify.breakpoint.name === 'xs'" /> 
</div>

Upvotes: 0

Bruce Sun
Bruce Sun

Reputation: 661

I was facing with the exact same problem, what's worse, mine is failing silently - I didn't see any errors.

Solution #1 move if else condition to the inner scope of <template>

As David Japan pointed out, you can check if else condition in the inner scope of slot-scope:

<template slot-scope="scope">
  <span v-if="options.columns">one thing...</span>
  <span v-else>something else.</span>
</template>

Solution #2 use v-slot instead of slot-scope

<template v-slot="scope" v-if="options.columns">
  one thing...
</template>
<template v-slot="scope" v-else>
  something else.
</template>

However I don't know why v-slot fixes it, I searched both in the official documentation and online but no clues.

Upvotes: 4

Related Questions