Home > Enterprise >  Setting VueJS inner component attrs based on prop
Setting VueJS inner component attrs based on prop

Time:08-01

Perhaps messing around with something obvious in VueJS syntax, but I can not make this Button.vue SFC to work:

<script setup>
defineProps({
    ...
    href: String,
    ...
});
</script>

...

<template>

<Link :href="href"
      :as="href == null ? 'button' : null"
      :type="href == null ? 'button' : null">
    <slot />
</Link>

</template>

I simply want that if there is href, Link is treated like an anchor, with href. But if no href prop coming, it is treated as a regular button, adding as="button" and type="button" to the Link component attrs.

But the browser console output that I get when instantiating a Button, e.g., with href="register" is this:

[Vue warn]: Unhandled error during execution of render function 
  at <Link href="http://myproject.test/register" as=null type=null  ...> 

href value is fine in this case, as href prop is provided, but look at the as=null type=null part... Looks like "null" is not treated as null.

Using Vue3 by the way :)

Any ideas? Thank you in advance

CodePudding user response:

If null is the issue then You can try this

<Link :href="href"
      :as="href == null ? 'button' : a"
      :type="href == null ? 'button' : a">
    <slot />
</Link>

In inertia Link component as props refer to HTML tag name

CodePudding user response:

Finally found the problem. Looking at Vue3 docs, I saw that optional props, when not present, evaluate as undefined, not as null like in Vue2.

Then, simply substituting every null appearance to undefined in my code did the trick.

  • Related