首页 > 解决方案 > setInterval 在 VueJs 中更改样式时仅工作一次

问题描述

我试图运行这个用按钮启动效果的简单代码。Effect 应该在每个新的 setInterval 刻度上交替使用“highlight”或“shrink”类(将相应的类附加到下面 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 秒更改一次,这很奇怪

标签: javascriptvue.js

解决方案


推荐阅读