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
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 }}
You'll face problems when the value is null/undefined as pointed out by David.
I'd use a computed variable to solve this problem.
Ex.
new Vue({
el: '#app',
data: {
prefix: 'Some value'
},
computed: {
prefixLength: function(){
if(this.prefix){
return prefix.length
}
return '';
}
}
})
Then you just use this in your template:
{{ prefix }} {{ prefixLength }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With