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
andli
tags siblings with thev-if
andv-else
conditionals and each with aslot
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
1 Answer
Reset to default 8Okay, 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
版权声明:本文标题:javascript - Dynamically change parent element tag on Vue JS 2 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744313142a2600128.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论