目录
- 应用场景
- 知识储备
- VUE代码示例
记录一下,以后有场景就不用百度,直接拿来用了~
应用场景
当前页面渲染之后,需要每隔几秒调用后台获取最新的数据展示等,那么就可以利用定时器每隔几秒请求一次接口,这个定时器属于Window对象属性,可以参考文档:Window对象属性文档
知识储备
会用到两个方法
1.设定定时操作方法【 文档】
//每三秒(3000 毫秒)处理点内容 :
var myTimer = setInterval(function(){ /*处理点内容*/ }, 3000);
2.清除定时器方法【文档】
clearInterval(myTimer);
VUE代码示例
<template>
<div><!-- 写该组建页面等内容 --></div>
</template>
<script>
export default {
props: {
//是否展示此组件
isShow: Boolean
},
data() {
return {
value:null,
codeTimer: null, // 定时器
codeTime: 12
}
},
watch: {
//只要变化为展示 则进行初始化
isShow(newVal, oldVal) {
if (newVal == true) {
this.init()
}
}
},
created() {
this.init()
},
methods: {
init() {
//获取值
this.getValueMethod()
//如果当前获取值为空,则执行定时器
if (this.value == null) {
this.initTimer()
}
},
// 开启定时器 通过codeTime的值来判断是否需要定时器
initTimer() {
this.codeTimer = window.setInterval(() => {
if (this.codeTime <= 0) {
// 通过window来清除定时器
window.clearInterval(this.codeTimer)
this.codeTimer = null
this.codeTime = 0
/* 清除定时的逻辑 */
if (this.value == null) {
this.$message.warning('您还是没获取到值,请核查!')
}
} else {
/* 未请求到接口,继续请求数据 */
console.info('进入定时器。。。。。')
this.getValueMethod()
//拿到值了就把定时器清除了
if (this.value) {
this.clearInitTimer()
}
this.codeTime--
}
}, 5000)
},
// 清除定时器
clearInitTimer() {
window.clearInterval(this.codeTimer)
this.codeTimer = null
this.codeTime = 0
},
// 获取值信息
getValueMethod() {
/*写调用后台的业务逻辑*/
}
}
}
</script>