Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access props values in data method in vuejs

I have the code (vuejs2) -

Vue.component('competetion-list', {
  template: `<div>{{totalCompetetions}}</div>`,
  props: ['values'],
  data: function () {
    return { totalCompetetions: this.values.length}
  }
})

Nothing is printed on the page but if I change the template value to

template: `<div>{{this.values.length}}</div>`

it prints 15. What am I doing wrong and how can I pass the props to the data?

Any help is much appreciated.

like image 303
paul-shuvo Avatar asked Mar 15 '17 05:03

paul-shuvo


3 Answers

I was unable to assign the prop values to data totalCompetetions in the following way -

data: function () {
    return { totalCompetetions: this.values.length}
  } 


But I was able to do it using the watch, computed, and methods properties.

With watch property -

  watch: {
    values: function(){
      this.totalCompetitions = this.values;
    }
  }

With computed property -

 computed:{
    competition:{
      get: function(){
        return this.values.length;
      }
    }

With methods property -

 methods:{
    competitionn: function(){
      return this.values.length;
    }
  }


But for computed and methods properties, I needed to set totalCompetetions in the following way -

For computed -

template: `<div><p>{{totalCompetitions = competition}}</p></div>` //without parenthesis

For methods -

template: `<div><p>{{totalCompetitions = competition()}}</p></div>` //with parenthesis
like image 157
paul-shuvo Avatar answered Nov 14 '22 23:11

paul-shuvo


You code does work.

I guess the problem is your parent component. Did you pass the values correctly? for example:

<competetion-list :values="[1, 2, 3]"></competetion-list>

Besides, for your case I'd say computed properties is a better solution.

computed: {
  totalCompetetions () {
    return this.values.length
  }
}
like image 30
CodinCat Avatar answered Nov 14 '22 22:11

CodinCat


From the data() method, you should be able to reference the component's properties using this.

Try following:

Vue.component('competetion-list', {
  template: `<div>{{totalCompetetions}}</div>`,
  props: ['values'],
  data: function () {
    var data = { totalCompetetions: this.values.length}
    return data
  }
})

As validly mentioned in the comment, if values array is changing later, you may have to put a watcher on the prop and inside watcher, set totalCompetetions as this.values.length.

like image 45
Saurabh Avatar answered Nov 14 '22 22:11

Saurabh