我对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>

这很好,我们只有一条线,但代价是当它不存在的时候,它什么都不绑定…
那么有没有办法有条件地绑定道具呢?
当然,我可以把这个公约包装成它自己的一个组成部分。但是,我发现它是什么,非常依赖于我正在使用的组件。我不喜欢在if-else语句之间复制和粘贴一段相同的代码来获得一个ref。
思想?思想?
例如
<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' };
  }
}

关于javascript - Vue:动态组件中条件 Prop 的约定?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52130437/

10-10 00:19
查看更多