I'm exploring the concept of generating random styles for an array of spans within a Vue component. By breaking down the message and utilizing v-for, I aim to showcase individual words in separate spans.
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();
}
});
The code snippet shows the application of randomly setting opacity for each span. Though it functions as expected in the example, hard-coding every random property is not ideal. Instead, employing a method or computed property is preferred. Here's an attempt at integrating a dynamic approach:
computedStyle: function() {
var o = Math.random().toFixed(2);
return {
'opacity': o,
};
}
This revised implementation involves adding the computed style to the spans like so:
'<div class="textFx"><span v-bind:style="computedStyle" v-for="words in wordArray">{{words}}</span></div>',
While the method does provide a random opacity value, it assigns the same randomness to all spans instead of generating individual values as seen with the hard-coded version.
To achieve randomization for each rendered span, how can I structure the component to accommodate a method or computed property that recalculates the Math.random value per span?