Reputation: 175
I'm trying to randomly generate styles for an array of spans using a vue component. I am splitting the message and using v-for to display the separate spans each with their own word.
const textFx = Vue.component('text-fx', {
template: '<div class="textFx"><span v-bind:style="{opacity: Math.random().toFixed(2)}" v-for="words in wordArray">{{words}}</span></div>',
props:['message'],
data: function() {
return {
wordArray: []
}
},
methods: {
setMessage: function() {
this.wordArray = this.parseMessage;
},
},
computed: {
parseMessage: function() {
var temp = this.message.split(" ");
for(var i = 0; i < temp.length - 1; i++) {
temp[i] += " ";
}
return temp;
},
},
created: function() {
this.setMessage();
}
});
As you can see, I'm setting the opacity of each span randomly. In that example, it works as intended, but I don't want to hard-code each random property like that of course, I would prefer to use a method or computed property. This is what I've tried adding to my component:
computedStyle: function() {
var o = Math.random().toFixed(2);
return {
'opacity': o,
};
}
And adding it to the span like this:
'<div class="textFx"><span v-bind:style="computedStyle" v-for="words in wordArray">{{words}}</span></div>',
This does technically work, it provides a random opacity value, but it applies the same random value to ALL spans, not individually like the hard-coded example did.
How can I structure this to allow for a method or computed property to re-compute the Math.random value for each span that is rendered?
Upvotes: 1
Views: 1313
Reputation: 55634
A computed property will only update its value if there is a change to any of it's dependent data properties. Since your computedStyle
has no dependent properties, the function to calculate it is only run once. That computed value won't change upon subsequent references.
Yours is a case where you would want to define a method which returns a style object instead of using computed property:
methods: {
getComputedStyle() {
return { opacity: Math.random().toFixed(2) };
}
}
Then, call the method when binding to the style like so:
<span v-bind:style="getComputedStyle()"></span>
Upvotes: 1