55

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.

1
  • length is obviously not a property on its own, it is computed from names. So what does that suggest to you? Commented Apr 2, 2018 at 17:19

1 Answer 1

91

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;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

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)
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?
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)
The 1st, in my case (I have a const instead of a let) it is perfect! Thanks.
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.