Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 764
John Lajer Avatar asked Nov 27 '16 22:11

John Lajer


2 Answers

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 }}
like image 84
David L Avatar answered Oct 16 '22 12:10

David L


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 }}
like image 38
Rodrigo Pereira Avatar answered Oct 16 '22 13:10

Rodrigo Pereira