VUE variable.length works in template, but gives console warning

John Lajer picture John Lajer · Nov 27, 2016 · Viewed 12k times · Source

I have a template in which I need to know the length of a provided variable...

{{ prefix }} {{ prefix.length }}

It spits out the correct information and seems to work just fine, but it gives this warning:

[Vue warn]: Error when evaluating expression "{ input_prefix: (prefix.length > 0)}": TypeError: Cannot read property 'length' of undefined (found in component: )

I would really like to do it right, and get rid of the warning. Any ideas?

Best regards John Lajer

Answer

David L picture David L · Nov 28, 2016

If prefix is null or undefined, by definition, it cannot have a length.

As a result, render the length via a ternary operator, using the length property if prefix exists and defaulting to zero if it does not exist:

{{ prefix && prefix.length ? prefix.length : 0 }}