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
          }
        }
    }
})
                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>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With