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.
Oct 7, 2018
7
Level 5
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
}
}
}
})``
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
Please or to participate in this conversation.