通过setInterval添加输入并不起作用

时间:2017-10-23 16:52:48

标签: javascript vue.js

请查看我的代码https://jsfiddle.net/kL5d4y08/ 当我点击按钮"改变"输入应从零开始计数以隐藏此输入,但是当我显示输入时,输入的值应再次等于0。 我怎么能这样做?

<script src="//unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <input :value="change" v-if="val1">
  <br/>
  <button @click="switchOn">Change</button>


</div>

var Main = {
    data() {
      return {
        val1: false,
                val2: 0,
      }
    },
    methods: {
    switchOn(){
    this.val1=this.val1==false?true:false
    },
    addUp(){
    setInterval(function(){this.val2++},2000);
    }
    },
    computed:{
    change(){ this.addUp(); return this.val2; }

    }
  }
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

1 个答案:

答案 0 :(得分:0)

基本上,您需要使用clearInterval来停止创建的间隔,并将计数器重置为零。

console.clear()
var Main = {
  data() {
    return {
      val1: false,
      val2: 0,
      interval: null
    }
  },
  methods: {
    switchOn(){
      this.val1 = !this.val1
      if (!this.val1){
        clearInterval(this.interval)
        this.interval = null
        this.val2 = 0
      } else {
       this.addUp()
      }
    },
    addUp(){
      this.interval = setInterval(() => this.val2++, 2000);
    }
  },
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
<script src="//unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <input v-model="val2" v-if="val1">
  <br/>
  <button @click="switchOn">Change</button>
  {{val1}}: {{val2}}

</div>