javascript - Vue:动态组件中条件道具的约定?
问题描述
我对 Vue 很陌生,所以如果我所做的事情很荒谬,请告诉我。
我的许多组件中的一个通用约定是这样的(仅显示代码的相关部分):
thing = {text:"some text", href: "https://a.link"}
<template>
<div>
<a v-if="thing.href" :href="thing.href">{{thing.text}}</a>
<span v-else>{{thing.text}}</span>
</div>
</template>
我不喜欢这个,因为thing.text
实际上可能有很多东西(不仅仅是文本)。
此外,我不喜欢渲染锚标记的冗余,即是否存在href
带有href
.
因此,我想像这样缩短和清理它:
<template>
<div>
<div :is="complexThing.href ? 'a' : 'span'" :href="complexThing.href">{{complexThing.lotsOfStuff}}</div>
</div>
</template>
这很好,我们只剩下一条线,但代价href
是当它不存在时被束缚...
那么有没有办法有条件地绑定一个道具?
当然,我可以将这个约定包装成它自己的组件。但是,我发现它是什么,很大程度上取决于我在其中使用它的组件。我不喜欢在 if-else 语句之间复制和粘贴一大块相同的代码只是为了获得一个 href。
想法?想法?
例如
<template>
<div :is="href ? 'a' : or" :href="href">
<!-- href=(unknown) will show in inspector if href is undefined -->
<slot></slot>
</div>
</template>
<script>
export default {
name: 'AnchorOr',
props: ['or', 'href']
}
</script>
<style>
</style>
然后可以像这样使用:
<AnchorOr class="inline-text" :or="span">{{text}}</AnchorOr>
<AnchorOr class="linked-module" :or="div">{{component}}</AnchorOr>
解决方案
在你的小例子中,我会保持原样;但是,如果{{ thing.text }}
是一个更大的模板部分,那么复制它是一个禁忌。
你通常会使用<component>
这样的情况:
<component v-bind="thingProps">{{ thing.text }}</component>
computed: {
thingProps() {
return this.thing.href
? { is: 'a', href: this.thing.href }
: { is: 'span' };
}
}
推荐阅读
- android - XML 中的数组:将一个数组作为一部分插入另一个数组
- javascript - Mongo shell db.model.find() 未显示所有文档
- javascript - 如何在 Vuetify v-treeview 中使用复合项目键
- activerecord - 如何在 yii2 中使用参数构造或初始化一个 activerecord 对象?
- arrays - 用于将 2 列相乘的 Google Sheets ArrayFormula 解决方案,其中之一是一列数字列表
- javascript - PostgreSQL SequelizeDatabaseError:无法识别的配置参数“表”
- django - 没有模块名称“编码”,在 Linux Apache2 上部署 Django
- javascript - Why does DOM element only update after event listener is finished? (pure js)
- php - 如何使用 shell_exec 执行 aws cli 命令?
- python - 有谁知道如何在 python 中计算 Coppock 曲线