Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference data variable from another data variable in Vue 2? [duplicate]

Tags:

vue.js

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.

like image 686
ace Avatar asked Apr 02 '18 16:04

ace


1 Answers

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;
    }
}
like image 64
Thomas Brd Avatar answered Nov 18 '22 17:11

Thomas Brd