代码之家  ›  专栏  ›  技术社区  ›  4r60_

如何停止VueJS上的间隔?[副本]

  •  1
  • 4r60_  · 技术社区  · 2 年前

    我确实试着用VueJS制作一个进度条,但当这个数等于100时,这个过程仍然在进行。当数据等于100%时,如何停止间隔?

    我使用了 console.log() 命令来检查代码是否正常工作,但它返回了错误的响应。

    顺致敬意,

    这是我的代码:

    HTML:

      <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
      
      <div id="app">
        <button v-on:click="startProgress">Start Progress</button>
        <br><br>
        <div class="progress" :style="{width : progressWidth + 'px'}"></div>
      </div>
    

    .progress{
        background-color: pink;
      transition: all 310ms ease;
        width: 0px;
        height: 20px;
      border-top-right-radius: 10px;
      border-bottom-right-radius: 10px;
    }
    

    VueJS:

    new Vue({
      el: '#app',
      data: {
        progressWidth : 0
      },
      methods: {
        startProgress : function(){
            var vm = this;
            setInterval(function(){
                vm.progressWidth+=10;   
            }, 150);
        vm.progressWidth= 20 ? console.log('20') : console.log('--');
        }
      },
    });
    

    如果您愿意,可以在JSFIDE上进行实时检查: https://jsfiddle.net/6j05p8Lb/46/

    1 回复  |  直到 2 年前
        1
  •  -1
  •   O.Badr    2 年前

    如所述 @Lawrence Cherone clearInterval function

    new Vue({
      el: '#app',
      data: {       
        progressWidth: 0    
      },
      methods: {
        startProgress: function() {
          const that = this;
          const timer = setInterval( function() {
            if (that.progressWidth >= 100) {
              clearInterval(timer);
            } else {
              that.progressWidth += 10;
            }
          }, 150);
        }
      }
    });
    .progress{
        background-color: pink;
      transition: all 310ms ease;
        width: 0px;
        height: 20px;
      border-top-right-radius: 10px;
      border-bottom-right-radius: 10px;
    }
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
      
      <div id="app">
        <button v-on:click="startProgress">Start Progress</button>
        <br><br>
        <div class="progress" :style="{width : progressWidth + 'px'}">{{ progressWidth }}</div>
      </div>