vue.js - 如何根据条件将模板代码块包装在不同的元素中?
问题描述
我的组件有 2 个道具:link
和isExternal
. 根据后者,我将把我的模板代码包装在一个<NuxtLink
(相当于 native Vue
<router-link>
)或一个<a>
元素中。
下面的代码通过使用两次相同的模板代码来实现这一点——这显然很糟糕。
然而我想不出一种简单的方法来优雅地做到这一点。任何想法?
<template>
<NuxtLink
v-if="!isExternal"
to="link"
>
<div
class="btn"
:style="{
'background-color': backgroundColor,
'color': textColor
}"
>
<img
v-if="image"
:src="image"
class="image"
>
<div>{{ text }}</div>
<svg-icon name="arrow-right" class="arrow" />
</div>
</NuxtLink>
<a
v-else
href="link"
target="_blank"
>
<div
class="btn"
:style="{
'background-color': backgroundColor,
'color': textColor
}"
>
<img
v-if="image"
:src="image"
class="image"
>
<div>{{ text }}</div>
<svg-icon name="arrow-right" class="arrow" />
</div>
</a>
</template>
解决方案
您可以使用component
这样的元素:
<template>
<component
:is="computedTag"
v-bind="computedProps"
>
<div
class="btn"
:style="{
'background-color': backgroundColor,
'color': textColor
}"
>
<img
v-if="image"
:src="image"
class="image"
>
<div>{{ text }}</div>
<svg-icon name="arrow-right" class="arrow" />
</div>
</component>
</template>
<script>
export default {
props: ['link', 'isExternal'],
computed: {
computedTag() {
return this.isExternal ? 'a' : 'nuxt-link';
},
computedProps() {
return this.isExternal
? { href: this.link, target: '_blank' }
: { to: this.link };
},
},
};
</script>
推荐阅读
- reactjs - 如何使用新的 auth0-spa.js 在不单击登录按钮的情况下重定向到 auth0?
- jenkins - jenkinsfile 页面加载事件
- javascript - 为什么我的 Ajax 调用没有超过 readystate 1?
- r - 如何计算R中数据框中每行出现多个字符串的次数
- jestjs - Jest 在测试期间没有显示绿色进度条
- python - TypeError:“模块”对象在 Python 3 中不可调用
- c++ - 在 C++ 中使用共享内存时出现 SIGSEGV 错误
- html - 页脚高度不固定的问题
- shell - 循环并组合两个文本文件的脚本
- javascript - 将纯 li 文本随机转换为纯 JavaScript 的可点击链接