业务场景:某个模块有多处数据刷新处理,为了减少 setInterval
或 setTimeout
线程的消耗,统一使用一个定时器,然后结合 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 = () => {
// ...
}