Conditional wrap component in Vue 3 pt.2
Alexander Nenashev
Posted on May 10, 2024
In the previous post we create a pretty idiomatic component that would work well for simple cases. Let's explore more options. What can be done to present our wrapper as a template as more DX friendly? Of course we could compile it runtime, but for a simple 1 level wrapper we could use the following:
export default function Wrap({isWrapped}, {slots}){
return isWrapped?
slots.default() :
slots.default().flatMap(vnode => vnode.children);
}
Wrap.props = { isWrapped: Boolean };
Usage:
<wrap :is-wrapped>
<div class="wrapper">
<p>
I'm wrapped
</p>
</div>
</wrap>
Yes, it looks non idiomatic, also it generates the wrapper's vnode every time even it's discarded, but it was an interesting case to explore for better DX.
In the next post we'll explore a more idiomatic option with using 2 slots for the content and wrapper.
💖 💪 🙅 🚩
Alexander Nenashev
Posted on May 10, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.