业务场景: 前端页面需要每几秒钟执行一个函数,或者每隔一段时间实现一些功能。这与后端的定时任务不同。后端定时任务只基于后端,没有request请求。前端相反,可以实现任意业务场景。
mounted(){
//在mounted 声明周期中创建定时器
const timer = setInterval(()=>{
// 这里调用调用需要执行的方法,1为自定义的参数,由于特殊的需求它将用来区分,定时器调用和手工调用,然后执行不同的业务逻辑
this.qryGridDAta("1")
}, 2000) // 每两秒执行1次
// 通过$once来监听定时器,在beforeDestroy钩子可以被清除
this.$once('hook:beforeDestroy',()=>{
// 在页面销毁时,销毁定时器
clearInterval(timer)
})
}
项目实例:
mounted() {
this.carousel()
},
beforeDestroy() {
clearInterval(this.timer)
this.timer = null
},
methods: {
carousel() {
request({
url: '/api/basedata/screenRefresh/getScreenRefreshById/1523200208182317056', // 经济运行监测 接口刷新时间
method: 'post'
}).then(res => {
this.timer = setInterval(() => {
this.$refs.Left.init()
this.$refs.Middle.init()
this.$refs.Right.init()
}, res.data.refreshtime)
})
}
}