Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 638
Merc Avatar asked Apr 16 '18 02:04

Merc


People also ask

What is conditional rendering in Vue?

Conditional rendering refers to the ability to render distinct user interface (UI) markup based on whether a condition is true or not. This notion is frequently used in contexts like showing or hiding components (toggling), switching application functionality, handling authentication and authorization, and many more.

What does $t mean in Vue?

Vuex is a state management pattern for vue. js. $t is the injected method from vue. js or Vue. i18n.

Does V-if destroy component?

v-if is "real" conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.


1 Answers

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

like image 110
Brian Lee Avatar answered Oct 26 '22 00:10

Brian Lee