Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue: Change class with the value of a variable in setInterval

I am learning Vue JS. I want to change class using setInterval. But can’t pass the changing value of Method to Computed Property. After two seconds class will change automatically with the changed value of "changeColor"

My Code:

HTML:

<div>
    <button @click="startEffect">Start Effect</button>
    <div id="effect" :class="myClass"></div>
</div>

CSS:

.highlight {
  background-color: red;
  width: 200px !important;
}

.shrink {
  background-color: gray;
  width: 50px !important;
}

Vue JS:

new Vue({
    el: '#exercise',
    data: {
        changeColor: false
    },

    methods : {
        startEffect: function() {
            setInterval(function(){
                 this.changeColor = !this.changeColor;
                 //alert(this.changeColor);
            }, 2000);

            //alert(this.changeColor);
        }
    },

    computed: {
        myClass: function() {
            return {
                highlight: this.changeColor,
                shrink: !this.changeColor
          }
        }
    }
})
like image 701
Mr. Perfectionist Avatar asked Mar 05 '23 06:03

Mr. Perfectionist


1 Answers

bind your function to the component...

 setInterval(function(){
                 this.changeColor = !this.changeColor;         
            }.bind(this), 2000);

and then you can do ...

<div id="effect" :class="[changeColor?'highlight':'shrink']"></div>
like image 94
Keith Nicholas Avatar answered Mar 18 '23 01:03

Keith Nicholas