[Vuejs]-Applying cycling colors in Vue

0👍

You dont need to use this to call your computed variable in view.

I would raise the function in a different way, so that it generates a random number every certain time and that number is the index of the array in your case generates a number between 0 and 1 and this return returns the color directly.

0👍

Your are executing 3 setTimeouts on the same time because your loop forEach will loop through that array in microseconds , so you will get the last color only which is green … this is one way how you can achieve that (run the snippet below) :

Vue.component('coloredComp', {
  props: ['color'],
  template: "<div id='box' :style='{backgroundColor : color}'></div>"
})

new Vue({
  el: '#app',
  data() {
    return {
      color: 'red'
    }
  },
  mounted() {
      let colors = ['yellow', 'red', 'green', 'blue']
      let i = 0;
      var int = setInterval(() =>{
        this.color = colors[i];
        i++;
        i == colors.length ? i=0 : '';
      }, 1000)
  }
})
#box {
  height: 200px;
  width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <colored-comp :color="color"></colored-comp>
</div>

0👍

Managed to get this working thanks to Dadboz!

Is there a way to add a transition into this as well? I’ve played around with gradients by adding something similar to ”linear-gradient(red, blue)’ in the array but wasn’t successful.

Looking to achieve a smooth transition between colors as opposed to inducing seizures.

Leave a comment