Vue: $attrs is undefined when component has no props

Created on 1 Aug 2017  ·  8Comments  ·  Source: vuejs/vue

Version

2.4.2

Reproduction link

https://jsfiddle.net/50wL7mdz/50757/

Steps to reproduce

Access $attrs as object within component context, when no props were provided.

What is expected?

$attrs is an object containing unrecognized props. Therefore I would expect an empty object, when no props are specified on component tag.

What is actually happening?

$attrs is undefined

bug

Most helpful comment

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

All 8 comments

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!

Was this page helpful?
0 / 5 - 0 ratings