setInterval在VueJs中更改样式时仅工作一次

时间:2019-03-15 01:31:18

标签: javascript vue.js

我正在尝试运行此简单的代码,以“按钮”开始“效果”。该效果应在每个新的setInterval刻度上交替使用“突出显示”或“收缩”类(将相应的类附加到下面的ID为“ effect”的div上),这是html:

<script src="https://npmcdn.com/vue/dist/vue.js"></script>

    <div id="exercise">
      <!-- 1) Start the Effect with the Button. The Effect should alternate the "highlight" or "shrink" class on each new setInterval tick (attach respective class to the div with id "effect" below) -->
      <div>
        <button @click="startEffect">Start Effect</button>
        <div id="effect" :class="effectClasses"></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;
}

这是JS文件:

    new Vue({
  el: '#exercise',
  data: {
        effectClasses :{
    highlight:false,
    shrink:true}
  },
  methods: {
    startEffect: function() {
    var vm = this;
    setInterval(function(){
       console.log('higlight 1:'+ vm.effectClasses.highlight);
        vm.effectClasses.highlight = !vm.effectClasses.highlight;      console.log('higlight 2 :'+ vm.effectClasses.highlight);

console.log('shrink 1 :' + vm.effectClasses.shrink);      
      vm.effectClasses.shrink =  !vm.effectClasses.shrink;
console.log('shrink 2 :' +vm.effectClasses.shrink);

    }, 1000);
    }
  }
});

控制台日志运行正常,但样式不会每1秒更改一次,这很奇怪

0 个答案:

没有答案