有没有办法根据条件将父元素定义为可选,但始终在Vue.js中显示其子元素?
例如:
<a :href="link">Some text</a>
Run Code Online (Sandbox Code Playgroud)
我想要实现的是以下DOM取决于 link
<a href="somelink">Some text</a> <!-- when link is truthy -->
Some text <!-- when link is falsy -->
Run Code Online (Sandbox Code Playgroud)
潜在解决方案
复制孩子们:
<a :href="link" v-if="link">Some text</a>
<template v-if="!link">Some text</template>
Run Code Online (Sandbox Code Playgroud)
但这不是一个好的解决方案,特别是因为可能有更多的内容而不仅仅是一个简单的文本.
编写我自己的组件,根据某些属性执行逻辑.但这似乎有些过分,并且必须足够灵活,以适应不同类型的元素类型或属性.
由于我不喜欢这些方法中的任何一种,我想知道是否没有更简单的解决方案.有任何想法吗?
str*_*str 14
经过一番挖掘,我发现了一种有效的方法,实际上非常简单.当您无法直接将组件绑定到HTML元素时,它使用实际意图使用的is特殊属性.
<a :href="link" :is="link ? 'a' : 'span'">Some text</a>
Run Code Online (Sandbox Code Playgroud)
这将导致以下任一情况:
<a href="somelink">Some text</a> <!-- when link is truthy -->
<span>Some text</span> <!-- when link is falsy -->
Run Code Online (Sandbox Code Playgroud)
对于 Vue 3,将执行以下操作:
<!-- `v-fragment` is globally registered -->
<component
:is="condition ? 'custom-component' : 'v-fragment'"
custom-component-prop
...
>
...
</component>
Run Code Online (Sandbox Code Playgroud)
// v-fragment.vue
<template>
<slot></slot>
</template>
<script>
export default {
inheritAttrs: false,
}
</script>
Run Code Online (Sandbox Code Playgroud)
对于 Vue 2,解决方法是:
<component
:is="condition ? 'custom-component' : 'div'"
custom-component-prop
...
>
...
</component>
Run Code Online (Sandbox Code Playgroud)
代价是,由于 Vue 2 不支持片段,因此会渲染像div/这样的额外元素。span
| 归档时间: |
|
| 查看次数: |
1650 次 |
| 最近记录: |