简体   繁体   中英

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.

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>` //without parenthesis

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
  }
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM