Mr. Perfectionist
Mr. Perfectionist

Reputation: 2746

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
          }
        }
    }
})

Upvotes: 4

Views: 6418

Answers (1)

Keith Nicholas
Keith Nicholas

Reputation: 44298

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>

Upvotes: 7

Related Questions