Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nafeeur10's avatar

How to pass data from Method to Computed Property

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:

#effect {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

.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
          }
        }
    }
})``
0 likes
7 replies
tykus's avatar

You can't pass arguments to a computed property, so use the method either to (i) update existing state, or (ii) set some (temporary) state on the instance data. Then ion the computed property function use that state to compute the value of myClass.

nafeeur10's avatar

Then what is your idea to solve this problem? I think it's easy. Just I have to update changeColor variable with setInterval function. and Computed property will use them and calculate.

tykus's avatar

If you think it's easy, then why are you asking the question?

I gave you the solution already:

either to (i) update existing state, or (ii) set some (temporary) state on the instance data. Then ion the computed property function use that state to compute the value of myClass.

D9705996's avatar
D9705996
Best Answer
Level 51

Instead of

<div id="effect" :class="myClass"></div>

You can use v-bind with an object

<div id="effect" v-bind:class="{ highlight: changeColor, shrink: !changeColor}"></div>

You then can just call your startEffect method. You don't need the computed property at all.

https://vuejs.org/v2/guide/class-and-style.html#Object-Syntax

1 like
nafeeur10's avatar

Yes you are right. But It is changing for one time!! It should change after two seconds.

D9705996's avatar

Could you share your updated code so I can see how it looks now you have made changes

Please or to participate in this conversation.