Vue.js 中的可选父元素 [英] Optional parent element in Vue.js

查看:27
本文介绍了Vue.js 中的可选父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以根据条件将父元素定义为可选元素,但始终在 Vue.js 中显示其子元素?

Is there any way to define the parent element as optional based on a condition but always show its children in Vue.js?

例如:

<a :href="link">Some text</a>

我想实现的是以下DOM取决于link

What I would like to achieve is the following DOM depending on link

<a href="somelink">Some text</a> <!-- when link is truthy -->
Some text                        <!-- when link is falsy -->

可能的解决方案

  • 复制子项:

  • Duplicate the children:

<a :href="link" v-if="link">Some text</a>
<template v-if="!link">Some text</template>

但这不是一个好的解决方案,特别是因为可能有更多的内容而不仅仅是简单的文本.

But that is not a good solution especially as there might be more content than just a simple text.

编写我自己的组件,根据某些属性执行逻辑.但这似乎有点矫枉过正,而且还必须对不同类型的元素类型或属性足够灵活.

Write my own component that does the logic depending on some attribute. But this seems overkill and also has to be flexible enough for different kind of element types or attributes.

由于我不喜欢这两种方法中的任何一种,我想知道是否有更简单的解决方案.有什么想法吗?

As I don't like either of these approaches, I wonder whether there is no simpler solution. Any ideas?

推荐答案

经过更多的挖掘,我找到了一种有效的方法,实际上非常简单.它使用 is 特殊属性 这实际上是在您无法直接将组件绑定到 HTML 元素时使用.

After some more digging, I found a way that works and is actually very simple. It uses the is special attribute that is actually meant to be used when you cannot bind components to HTML elements directly.

<a :href="link" :is="link ? 'a' : 'span'">Some text</a>

这将导致以下任一情况:

This will result in either of the following:

<a href="somelink">Some text</a> <!-- when link is truthy -->
<span>Some text</span>           <!-- when link is falsy -->

这篇关于Vue.js 中的可选父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆