7

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.

1
  • 2
    At the time of initialization, prop may or may not contain the valid data, watch for changes in the prop and update it accordingly. Commented Mar 15, 2017 at 5:36

3 Answers 3

10

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

Comments

4

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

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.