代码之家  ›  专栏  ›  技术社区  ›  SumNeuron

Vue:动态组件中条件道具的约定?

  •  1
  • SumNeuron  · 技术社区  · 7 年前

    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公司 当它不存在的时候,什么都没有。。。

    那么有没有办法 道具?

    思想?思想?

    例如

    <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>
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Decade Moon    7 年前

    在你的小例子中,我会保持原样;但是如果 {{ thing.text }} 取而代之的是一个较大的模板部分,然后复制它是一个不-不。

    <component> 对于这种情况:

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