2.4.2
https://jsfiddle.net/50wL7mdz/50757/
Access $attrs as object within component context, when no props were provided.
$attrs is an object containing unrecognized props. Therefore I would expect an empty object, when no props are specified on component tag.
$attrs is undefined
Out of curiosity, what problem are you facing by having an undefined $attrs? Are you accessing $attrs.something? (if so, why?)
edit: I'm also asking because having $attrs equal undefined when there're no attrs can actually be useful
@greegus, in case you're doing something like if ($attrs.myProp) you can do if ($attrs?.myProp) by using babel-plugin-transform-optional-chaining.
I would judge this to be expected behaviour, but it's debatable.
ping @greegus
Just ran into this and it was definitely unexpected for me that $attrs should ever be undefined.
For example, if you were writing a todo app that starts out with no todos, it would be very strange to make the list begin as undefined instead of []. You'd have to add if statements (or optional chaining) all over your app. This case is similar.
For niche cases when a user wants to check if any $attrs exist, it'd still be possible to use Object.keys($attrs).length, so that case is still covered.
The part that really convinces me this is a bug though, is that $attrs _is_ set to an empty object when a prop is passed to a component - as the OP points out. So currently, really checking if any $attrs exist would require both strategies:
$attrs && Object.keys($attrs).length
@chrisvfritz convinced me - it's a bug.
@LinusBorg Looks like no one is working on this bug currently. May I have a pr for this?
Sure!
Most helpful comment
Just ran into this and it was definitely unexpected for me that
$attrsshould ever beundefined.For example, if you were writing a todo app that starts out with no todos, it would be very strange to make the list begin as
undefinedinstead of[]. You'd have to addifstatements (or optional chaining) all over your app. This case is similar.For niche cases when a user wants to check if any
$attrsexist, it'd still be possible to useObject.keys($attrs).length, so that case is still covered.The part that really convinces me this is a bug though, is that
$attrs_is_ set to an empty object when a prop is passed to a component - as the OP points out. So currently, really checking if any$attrsexist would require both strategies: