Engineering

Conditionally Wrapping Content in Vue 3: Link-or-Span, h() and a Reusable ConditionalWrap

How to conditionally wrap content in Vue 3 with <component :is>, render functions and a typed ConditionalWrap component using slots, plus common pitfalls.

By Japan Gor · · 6 min read

A common UI requirement: render some content inside a wrapper element only when a condition is true. A card title should be a link if the item has a URL and plain text otherwise. A table cell should sit inside a tooltip only when the text is truncated. A list item should be wrapped in a <RouterLink> only for signed-in users. The naive solution duplicates the inner markup in a v-if and a v-else branch, and those copies drift apart over time. This tutorial shows cleaner options in Vue 3, from the built-in <component :is> to a reusable, typed ConditionalWrap component, and explains the pitfalls you'll hit along the way.

The problem with duplicated branches

Here's the version most of us write first:

<template>
  <a v-if="href" :href="href" class="title">
    <IconStar v-if="featured" />
    {{ label }}
  </a>
  <span v-else class="title">
    <IconStar v-if="featured" />
    {{ label }}
  </span>
</template>

It works, but the content is written twice. Every future change (a new badge, a class, an aria attribute) has to be made in both places. Let's remove the duplication.

Option 1: <component :is> for link-or-span

Vue's built-in <component> special element renders whatever its is prop names: an HTML tag string or a component. This handles the "which element?" case neatly:

<script setup lang="ts">
defineProps<{ href?: string; label: string; featured?: boolean }>()
</script>

<template>
  <component :is="href ? 'a' : 'span'" :href="href" class="title">
    <IconStar v-if="featured" />
    {{ label }}
  </component>
</template>

When href is undefined, Vue doesn't render the attribute at all, so the <span> doesn't receive a stray href. You can also pass a component, for example :is="to ? RouterLink : 'span'" with :to="to", after importing RouterLink from vue-router. The Vue guide's section on dynamic components covers the basics.

Limitation: <component :is> always renders some element. It answers "a or span?", not "wrapper or nothing?". For the second case you need a different approach.

Option 2: a template-based ConditionalWrap

The goal is a component used like this:

<ConditionalWrap :when="!!user" :tag="RouterLink" :to="`/profile/${user?.id}`">
  <Avatar :user="user" />
</ConditionalWrap>

When when is true, the slot content is wrapped in the given tag; otherwise the slot content is rendered on its own. A template version using slots:

<!-- ConditionalWrap.vue -->
<script setup lang="ts">
import type { Component } from 'vue'

defineOptions({ inheritAttrs: false })

withDefaults(
  defineProps<{
    when: boolean
    tag?: string | Component
  }>(),
  { tag: 'div' }
)
</script>

<template>
  <component :is="tag" v-if="when" v-bind="$attrs">
    <slot />
  </component>
  <slot v-else />
</template>

Key details:

  • inheritAttrs: false stops Vue from automatically applying attributes like to, href or class to the root. Because this component can render a fragment (multiple root nodes) in the unwrapped case, automatic fallthrough wouldn't work anyway, and Vue warns about attributes it can't place. We bind $attrs explicitly to the wrapper only. See Fallthrough Attributes.
  • defineOptions is available in <script setup> from Vue 3.3. On older versions, add a separate plain <script> block that exports { inheritAttrs: false }.
  • The default slot appears twice in the template, but only one branch renders at a time, so the content is never duplicated in the DOM.

Option 3: a render function with h()

Templates are the recommended default in Vue, but render functions are a natural fit for components whose whole job is to decide structure. The Vue guide covers them in Render Functions & JSX. The same component written with h():

// ConditionalWrap.ts
import { defineComponent, h, type Component, type PropType } from 'vue'

export default defineComponent({
  name: 'ConditionalWrap',
  inheritAttrs: false,
  props: {
    when: { type: Boolean, required: true },
    tag: {
      type: [String, Object, Function] as PropType<string | Component>,
      default: 'div'
    }
  },
  setup(props, { slots, attrs }) {
    return () => {
      const children = slots.default?.()
      if (!props.when) {
        // Render the slot content with no wrapper (an array becomes a fragment).
        return children
      }
      return typeof props.tag === 'string'
        ? h(props.tag, attrs, children)               // native element: pass children
        : h(props.tag, attrs, { default: () => children }) // component: pass slots
    }
  }
})

Why the typeof branch? When you call h() with a native tag, the third argument is the element's children. When you call it with a component, the recommended form is a slots object of functions, so the child component can render the slot lazily. Passing a plain array to a component works but produces a performance warning in development.

Usage is identical to the template version:

<script setup lang="ts">
import { RouterLink } from 'vue-router'
import ConditionalWrap from './ConditionalWrap'

const props = defineProps<{ url?: string; title: string }>()
</script>

<template>
  <ConditionalWrap :when="!!props.url" tag="a" :href="props.url" target="_blank" rel="noopener">
    <h3>{{ props.title }}</h3>
  </ConditionalWrap>
</template>

Template or render function?

Template + <component :is>Render function with h()
Readability for most teamsHigherLower
Compiler optimisationsYes (template compilation)You write the vnodes yourself
Flexibility for structural logicGoodHighest
TypeScript propsdefineProps<...>()PropType casts

For a component this small, either is fine. Pick the one your team will find easiest to maintain.

Practical examples

Tooltip only when needed

<ConditionalWrap :when="isTruncated" :tag="Tooltip" :content="fullText">
  <span class="truncate">{{ fullText }}</span>
</ConditionalWrap>

Link only for authorised users

<ConditionalWrap :when="canEdit" :tag="RouterLink" :to="`/docs/${doc.id}/edit`">
  <DocCard :doc="doc" />
</ConditionalWrap>

Here Tooltip and DocCard stand in for your own components.

Pitfalls to watch for

1. Toggling the condition remounts the content

When when flips from false to true, the virtual DOM tree changes shape: the content moves from the top level into the wrapper. Vue can't patch across that structural change, so it unmounts and remounts the slot content. Any local component state inside (form input, scroll position, an open dropdown) is lost. If the condition changes often and the content is stateful, consider keeping the wrapper always present and toggling its behaviour instead (for example, a <span> that becomes a link via :is).

2. Attributes on the unwrapped branch

With inheritAttrs: false, attributes such as class go only to the wrapper. When unwrapped, they're dropped. That's usually what you want (a href on nothing makes no sense), but if you need styling on the content in both cases, put the class on the slot content itself.

3. Event listeners

In Vue 3, listeners like @click are part of $attrs, so they follow the same rule: attached to the wrapper when present, dropped otherwise. Put listeners that must always work on the inner content.

4. Accessibility

A conditional link changes semantics. Don't wrap interactive elements (buttons, inputs) inside an <a>, and make sure a non-link version isn't styled to look clickable. If you swap a <button> for a <span>, keyboard users lose focusability unless you handle it.

5. Multiple root nodes inside a single-root wrapper

Some wrapper components expect exactly one child (certain transition or tooltip components, for example). If your slot content has several root nodes, wrap it in an element or check that component's documentation.

6. Boolean coercion in templates

Pass a real boolean to when: :when="!!url" rather than :when="url". With a typed Boolean prop, Vue will warn in development about a string value, and being explicit makes the intent obvious.

Testing the component

With Vue Test Utils, a quick check of both branches:

import { mount } from '@vue/test-utils'
import ConditionalWrap from './ConditionalWrap'

it('wraps when true', () => {
  const w = mount(ConditionalWrap, {
    props: { when: true, tag: 'a' },
    attrs: { href: '/x' },
    slots: { default: '<b>hi</b>' }
  })
  expect(w.html()).toContain('<a href="/x"><b>hi</b></a>')
})

it('renders bare content when false', () => {
  const w = mount(ConditionalWrap, {
    props: { when: false, tag: 'a' },
    attrs: { href: '/x' },
    slots: { default: '<b>hi</b>' }
  })
  expect(w.find('a').exists()).toBe(false)
  expect(w.find('b').text()).toBe('hi')
})

Summary

When you only need to switch which element renders, <component :is> is the simplest tool. When the wrapper should sometimes disappear entirely, a small ConditionalWrap component removes the duplicated branches: write it with a template and v-bind="$attrs", or with a render function and h(). Turn off attribute inheritance, pass slots correctly to component wrappers, and remember that toggling the condition remounts the inner content. Those few details are what separate a helper that works in a demo from one you can use across an app.

More guides