DEV Community

Alexander Nenashev
Alexander Nenashev

Posted on

1

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 };
Enter fullscreen mode Exit fullscreen mode

Usage:

  <wrap :is-wrapped>
    <div class="wrapper">
      <p>
        I'm wrapped
      </p>
    </div>
  </wrap>
Enter fullscreen mode Exit fullscreen mode

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.

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

If this post resonated with you, feel free to hit ❤️ or leave a quick comment to share your thoughts!

Okay