Using templates slots & conditions when migrating to Vue 3 syntax #8551
-
I couldn't find any example, issue or discussion about this one, I hope I didn't misunderstand something. Given a Modal component: <div>
<header>
<slot name="title" />
</header>
<main>
<slot />
</main>
<footer>
<slot name="footer" />
</footer>
</div> We used to use it like this in Vue 2: <Modal>
<Loader v-if="isLoading" />
<template v-else />
<h2 slot="title">Hello world!</h2>
<p>Default slot content...</p>
<button slot="footer">Close</button>
</template>
</Modal> Now that we're supposed to use <Modal>
<Loader v-if="isLoading" />
<template v-if="!isLoading" #title>
<h2>Hello world!</h2<
</template>
<template v-if="!isLoading">
<p>Default slot content...</p>
</template>
<template v-if="!isLoading" #footer />
<button slot="footer">Close</button>
</template>
</Modal> There has to be a better way, right? Thanks :) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
When Vue processes a Here is a solution to warp a <!-- Modal.vue -->
<template>
<div>
<slot />
</div>
</template> <!-- ModalContent.vue -->
<template>
<header>
<slot name="title" />
</header>
<main>
<slot />
</main>
<footer>
<slot name="footer" />
</footer>
</template> And you should able to use it as following <!-- App.vue -->
<template>
<Modal>
<ModalContent v-if="isLoading">Loading...</ModalContent>
<ModalContent v-else>
<template #title>
<h2>Hello World!</h2>
</template>
<p>Default slot content...</p>
<template #footer>
<button>Close</button>
</template>
</ModalContent>
</Modal>
</template> I just make a playground with the above source, you can give a try. if my comment is helpful, please feel free to mark it as answer. 😃 |
Beta Was this translation helpful? Give feedback.
When Vue processes a
<template>
tag with av-if
orv-else
, it's expected to directly contain the elements that should be rendered under that condition. Nested<template>
tags are not treated as a single unit in this context.Here is a solution to warp a
<ModalContent>
component inside<Modal>
component.And you should able to use it as following