mardi 23 mai 2017

v-bind behavior with Math.random not as expected

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"></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"></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?




Aucun commentaire:

Enregistrer un commentaire