我以恒定的时间间隔从 API 获取 Nuxt 组件中的日志,然后显示它。
setInterval当组件未显示时如何停止该方法(并在再次显示时重新启动它)?
<template>
<v-container>
<v-row>
<v-col class="text-center"> Logs </v-col>
</v-row>
<v-row>
<v-col>{{ logs }}</v-col>
</v-row>
</v-container>
</template>
<script>
export default {
data() {
return {
logs: null,
}
},
mounted() {
setInterval(this.getLogs, 2000)
},
methods: {
async getLogs() {
console.log('getting logs')
await this.$axios
.get('logs/custom')
.then((res) => (this.logs = res.data))
.catch((err) => {
console.log(err)
})
},
},
}
</script>
Run Code Online (Sandbox Code Playgroud)
Nic*_*wes 11
将调用setInterval()移动到mounted()生命周期挂钩中,并将其保存到变量中。在destroyed()挂钩中,调用clearInterval()变量。
mounted() {
this.interval = setInterval(this.getLogs, 2000)
},
data() {
return {
interval: null
}
},
destroyed() {
clearInterval(this.interval)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3590 次 |
| 最近记录: |