admin管理员组

文章数量:1401849

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?

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?

Share Improve this question edited Jul 15, 2018 at 8:14 sandrina-p asked Jul 11, 2018 at 20:08 sandrina-psandrina-p 4,1709 gold badges37 silver badges66 bronze badges 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. – obermillerk 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 :/ – sandrina-p Commented Jul 15, 2018 at 8:13
  • did you end up getting it working? – obermillerk Commented Jul 19, 2018 at 21:49
Add a ment  | 

1 Answer 1

Reset to default 8

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

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

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

The :is property can be delegated to a puted 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 ponent 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/v2/guide/ponents.html#Dynamic-Components
There's also a link there to more details about dynamic ponents if you need further reading.

本文标签: javascriptDynamically change parent element tag on Vue JS 2Stack Overflow