简体   繁体   中英

Vue.js: Don't render attributes if value is empty (e.g.: to="" or type="")

I have Button component which renders a nuxt-link or a button depending if you provide some attribute like to or type .

<div class="Btn">
  <component
    :class="['Btn__button', createAppearanceClasses]"
    v-on:click="click"
    :disabled="disabled"
    :is="type"
    :to="to"
    :href="external ? to : false"
    :target="target"
    :type="buttonType"
    >
    <slot />
  </component>
</div>

(Whereas the type is a computed property to return a nuxt-link for internal links, a a tag if it is an external link or a button if these properties are not defined)

Now we sometimes render some Buttons which open a Modal or submit. There we don't pass any type or to attribute:

<Btn :class="'FlexContent__button'" 
  :appearance="['rounded-corners']"
  v-on:click.native="openOverlay" 
>    
 {{ component.text }}
</Btn>

In the rendered HTML I get:

<button disabled to="" target="" type="" class="Btn__button Btn__button--rounded-corners">

If I validate this I get errors concerning these empty attributes: Attribute to not allowed on element button at this point.

How can I render the attribute to="" only if I have an actual value passed to the Btn component?

I was thinking about something like this, but this does not work: (to ? ':to="to"' : '') So I need some other solution for this.

Thanks in advance for hints.

cheers

Any attribute that is bound using v-bind to a value that is null, undefined, or false will not be rendered in the element.

Attributes and v-bind

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM