3

How do I switch between different parents element depending on a prop conditional, keeping its content the same?

Example: If Item has isRouter prop, it renders router-link with the needed attributes, otherwise it renders a simple li element.

/* Item.vue */

<router-link v-if="isRouter" tag="li" :to="to" active-class="is-active">
<li v-else>
    /* some html */
    <slot></slot>
    /* more html */
</li>
</router-link>

// View.vue
<list>
  <item isRouter to="/new">
    Breaking News
  </item>
  <item>
    Orange
  </item>
</list>

Is this possible to do? What approach do you advice me to follow?

3
  • I don't believe it's possible to dynamically change the tag type like that. I think you would be fine if you made the router-link and li tags siblings with the v-if and v-else conditionals and each with a slot in them, though I haven't tested that. Something to try. Commented Jul 15, 2018 at 7:06
  • @obermillerk it's kind what' I've done so far, the problem is the inside content has much more content beside the slot, so there's some duplication :/ Commented Jul 15, 2018 at 8:13
  • did you end up getting it working? Commented Jul 19, 2018 at 21:49

1 Answer 1

8

Okay, so I actually did find a way to do what you want!

Using vue's component tag and vbind:is property (or :is shorthand).

<component :is="isRouter ? 'router-link' : 'li'" :to="to">
  <!-- repeated content -->
  <slot></slot>
  <!-- more repeated content -->
</component>

The :is property can be delegated to a computed property if you need. And be aware that any props you want to pass to the router-link will need to be defined for the component tag, but you can have these conditional as well if you don't want them on the li.

This is where I found it: https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components
There's also a link there to more details about dynamic components if you need further reading.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.