背景
子组件: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失效?
时隔两年多,这个问题还是存在
简单来说,vue2 封装了
setTimeout
函数,导致setTimeout
返回一个对象。对象含有 _id 属性,将这个属性作为
clearTimeout
参数即可or
在 vue 动手之前,先一步的得到原先函数的引用
使用新的引用即可正常使用