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.
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;
}
}
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?length is read only (you cannot directly set a computed value because it's bind to a data variable)
lengthis obviously not a property on its own, it is computed fromnames. So what does that suggest to you?