首页 > 为什么vue子组件clearTimeout会失效?

为什么vue子组件clearTimeout会失效?

背景
子组件:toast组件,显示信息,3000ms后自动消失

设计
toast子组件进行如果在3000ms内调用两次,第一次的setTimeout销毁掉,然后开始第二次的setTimeout

代码
子组件:

<template>

  <div id="ximi_toast">
    <!-- 超时 -->
    <toast :show="0 == tType" type="text" :time="tTime" :width="tWidth">{{ tString }}</toast>

    <toast :show="1 == tType" type="success" :time="tTime" :width="tWidth">{{ tString }}</toast>

    <toast :show="2 == tType" type="cancel" :time="tTime" :width="tWidth">{{ tString }}</toast>

    <toast :show="3 == tType" type="warn" :time="tTime" :width="tWidth">{{ tString }}</toast>
    
  </div>
</template>

<script>
// FIXME: timeout不能clear

import toast from 'vux/src/components/toast'

module.exports = {
  props:{
    tType: {
      type: Number,
      twoWay: true
    },
    tTime: {
      type: Number
    },
    tWidth: {
      type: String
    },
    tString: {
      type: String,
      twoWay: true
    }
  },
  components: {
    "toast": toast
  },
  data () {
    return {
      fuckingTimer: null
    }
  },
  watch: {
    tType: function (val) {
      if (val != -1) {
        this.resetToast()
      }
    },
    tString:  function (val) {
      var _this = this;
      clearTimeout(this.fuckingTimer);
      console.log(this.fuckingTimer);
      // this.fuckingTimer = null ;
      this.fuckingTimer = setTimeout(function(){
        _this.tType = -1
      }, this.tTime);
    }
  },
  methods: {
    resetToast: function(){
      var _this = this;
      clearTimeout(this.fuckingTimer);
      console.log(this.fuckingTimer);
      // this.fuckingTimer = null ;
      this.fuckingTimer = setTimeout(function(){
        _this.tType = -1
      }, this.tTime);
    }
  }
}
</script>

问题 && 现在的效果
调用第一次,出现第一次的toast信息,在大约2000ms的时候,设置新的toast信息,可是clearTimeout没有生效,第一次和第二次toast的信息总时间长度变成了3000ms。而没有达到第二次toast信息是3000ms,总时间是5000ms。

请问是什么原因导致clearTimeout失效?


为什么几个toast要共用一个timer呢。。
因为你没有把外部调用代码一起贴上来,不太好判断你这里的2000ms以及3000ms具体是什么情况。
但是就功能设计来说,建议你应该把timer放到toast内部去,每个toast各自维护一个timer,重复的时候用clearTimer
如果业务导致不能放到toast,那么也不应该在watch和methods里面写两套逻辑去clearTimer,这样逻辑有点混乱

【热门文章】
【热门文章】