我正在学习Vue JS。我想使用setInterval
更改班级。但是无法将Method
的变化值传递给Computed Property
。两秒钟后,课程将自动更改,更改后的值为“ changeColor
”
我的代码:
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
}
}
}
})
答案 0 :(得分:3)
将功能绑定到组件...
setInterval(function(){
this.changeColor = !this.changeColor;
}.bind(this), 2000);
然后您就可以...
<div id="effect" :class="[changeColor?'highlight':'shrink']"></div>