- 在data中定义timer来接收定时器,方便清除。
- 在mounted中挂载定时器,模拟轮询向后台发送请求来更新数据。
- 在destroyed里面清除定时器。
<template>
<div>
<h2 style="font-weight:1400;">{{num}}</h2>
</div>
</template>
<script>
export default {
name: 'PageTwo',
data () {
return {
num: 10,
// 定义数据来接收定时器,方便清除
timer: null
}
},
mounted () {
// 挂载计时器,模拟轮询向后台发送请求来更新数据。
this.timer = setInterval(() => {
this.num++
}, 500)
},
// 切换路由销毁组件时,清除timer
destroyed () {
if (this.timer) {
console.log('timer被清除了')
this.timer = null
}
}
}
</script>