vue3定时刷新

业务场景:某个模块有多处数据刷新处理,为了减少 setIntervalsetTimeout 线程的消耗,统一使用一个定时器,然后结合 watch 监听实现刷新同步,更具体的可以再结合各个接口的请求时间来判定是否刷新。

stores/home.ts

import { ref } from 'vue'

// 当前时间
const curTime = ref<number>(Date.now())

const setCurTime = () => {
  curTime.value = Date.now()
}

Home.vue

import { useHomeStore } from '@/stores/global'

const homeStore = useHomeStore()

// 定时器,10秒更新一次
const timer = setInterval(() => {
  homeStore.setCurTime()
}, 1e4)

// 卸载
onUnmounted(() => {
  clearInterval(timer)
})

Home.vue 或 Children.vue

import { storeToRefs } from 'pinia'

const homeStore = useHomeStore()

const { curTime } = storeToRefs(homeStore)

// 监听当前时间变动
watch(curTime, () => {
  getDataA()
  getDataB()
})

const getDataA = () => {
  // ...
}

const getDataB = () => {
  // ...
}
PS:写作不易,如要转裁,请标明转载出处。
%{ comment.page.total }条评论

微信小程序:前端开发宝典

相关笔记
工具操作
  • 内容截图
  • 全屏
登录
注册
回顶部