简体   繁体   中英

Setting VueJS inner component attrs based on prop

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 , eg, 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

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

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.

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