53

I have this in vue data:

data() {
    return {

      names: [],
      length: names.length,
}

But this does not work as RefereneError ( names is undefined ) is thrown. I used this.names but makes no difference.

ace
  • 11,526
  • 39
  • 113
  • 193
  • `length` is obviously not a property *on its own*, it is **computed** from `names`. So what does that suggest to you? – connexo Apr 02 '18 at 17:19

1 Answers1

90

You need to do something like this to make it work:

#1st way

data() {
    let defaultNames = [];
    return {
      names: defaultNames,
      length: defaultNames.length
    }
}

#2nd way — using computed data (the better way):

data() {
    return {
      names: [],
    }
},
computed: {
    length() {
        return this.names.length;
    }
}
Tobias Feil
  • 2,399
  • 3
  • 25
  • 41
Thomas Brd
  • 1,253
  • 9
  • 10
  • 10
    With the specific example information the 1st way is probably not ideal (is length even reactive there? i haven't checked). But there are other scenarios where the 1st way is perfectly valid and maybe preferable (like if you're directly manipulating data based on other data at the time of initialization) – Damon Sep 28 '18 at 13:37
  • I'm curious about the binding as well. In the first approach it seems like `names` and `length` are decoupled. In the second approach it seems like `length` would be bound to `names`. But what about vice versa? Is `length` read only in the second approach? – sfmiller940 Aug 08 '19 at 18:59
  • Hi sfmillier940, yes indeed in the second approach `length` is read only (you cannot directly set a computed value because it's bind to a `data` variable) – Thomas Brd Aug 13 '19 at 09:50
  • The 1st, in my case (I have a const instead of a let) it is perfect! Thanks. – Uncoke Aug 06 '20 at 16:34
  • 3
    For me 1st way was useful, as I don't need the property to be reactive, i just need to initialize a selected_item based on an items_array. Thanks – Elias Escalante Oct 16 '20 at 15:51