DEV Community

Alexander Nenashev
Alexander Nenashev

Posted on Edited on

Conditional wrap component in Vue 3 pt.2

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:

See on Vue SFC Playground

export default function Wrap({isWrapped}, {slots}){
  return isWrapped? 
    slots.default() : 
    slots.default().flatMap(vnode => vnode.children);
}

Wrap.props = { isWrapped: Boolean };
⚽ Live Match: alexander nenashev/conditional wrap component in vue pt aco - Pertandingan Hari Ini ⚽ Live Match: alexander nenashev/conditional wrap component in vue pt aco - Pertandingan Hari Ini

Usage:

  <wrap :is-wrapped>
    <div class="wrapper">
      <p>
        I'm wrapped
      </p>
    </div>
  </wrap>
⚽ Live Match: alexander nenashev/conditional wrap component in vue pt aco - Pertandingan Hari Ini ⚽ Live Match: alexander nenashev/conditional wrap component in vue pt aco - Pertandingan Hari Ini

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.

Top comments (0)