首页 > 解决方案 > 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>

标签: javascriptvue.jsvuejs2vue-component

解决方案


在你的小例子中,我会保持原样;但是,如果{{ thing.text }}是一个更大的模板部分,那么复制它是一个禁忌。

你通常会使用<component>这样的情况:

<component v-bind="thingProps">{{ thing.text }}</component>
computed: {
  thingProps() {
    return this.thing.href
      ? { is: 'a', href: this.thing.href }
      : { is: 'span' };
  }
}

推荐阅读