4

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
          }
        }
    }
})
Mr. Perfectionist
  • 2,605
  • 2
  • 24
  • 35
  • 2
    Possible duplicate of [how to use setInterval in vue component](https://stackoverflow.com/questions/43335477/how-to-use-setinterval-in-vue-component) – You Nguyen Oct 07 '18 at 11:50

1 Answers1

7

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>
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156