vue实现settime刷新

Vue 中使用 setTimeout 实现刷新功能
在 Vue 中可以通过 setTimeout 结合 Vue 的响应式特性实现定时刷新功能。以下是几种常见实现方式:
基础用法:组件内定时刷新数据
export default {
data() {
return {
timer: null,
dataList: []
}
},
mounted() {
this.startRefresh()
},
beforeDestroy() {
clearTimeout(this.timer)
},
methods: {
fetchData() {
// 模拟数据请求
axios.get('/api/data').then(res => {
this.dataList = res.data
})
},
startRefresh() {
this.fetchData()
this.timer = setTimeout(() => {
this.startRefresh()
}, 5000) // 5秒刷新一次
}
}
}
使用 Vue 的 nextTick 优化
methods: {
refreshWithNextTick() {
this.fetchData()
this.$nextTick(() => {
this.timer = setTimeout(this.refreshWithNextTick, 3000)
})
}
}
结合 async/await 实现
async refreshAsync() {
try {
await this.fetchData()
this.timer = setTimeout(this.refreshAsync, 10000)
} catch (error) {
console.error('刷新失败', error)
this.timer = setTimeout(this.refreshAsync, 30000) // 失败后延长间隔
}
}
注意事项
- 务必在
beforeDestroy或onUnmounted(Vue3) 生命周期中清除定时器 - 避免在短时间内频繁刷新导致性能问题
- 对于需要精确计时的场景,建议使用
setInterval替代递归的setTimeout - 在 Vue3 Composition API 中可以使用
onMounted和onUnmounted实现相同功能
Vue3 Composition API 实现
import { ref, onMounted, onUnmounted } from 'vue'
export default {
setup() {
const data = ref([])
let timer = null
const fetchData = async () => {
data.value = await axios.get('/api/data')
}
onMounted(() => {
const startRefresh = () => {
fetchData()
timer = setTimeout(startRefresh, 8000)
}
startRefresh()
})
onUnmounted(() => {
clearTimeout(timer)
})
return { data }
}
}







