【问题标题】:Vue: Change class with the value of a variable in setIntervalVue:使用setInterval中的变量值更改类
【发布时间】:2019-03-12 06:55:03
【问题描述】:

我正在学习 Vue JS。我想使用setInterval 更改课程。但是不能将Method的变化值传递给Computed Property。两秒后,class 将自动更改为“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
          }
        }
    }
})

【问题讨论】:

标签: vue.js vuejs2 computed-properties


【解决方案1】:

将你的函数绑定到组件...

 setInterval(function(){
                 this.changeColor = !this.changeColor;         
            }.bind(this), 2000);

然后你就可以做...

<div id="effect" :class="[changeColor?'highlight':'shrink']"></div>

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 2020-07-04
    • 2021-04-24
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    相关资源
    最近更新 更多