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}
}
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;
}
}
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With