33 lines
907 B
JavaScript
33 lines
907 B
JavaScript
import { onMounted, onBeforeUnmount } from 'vue'
|
|
import { onAppReturnFromBackground } from '@/utils/backgroundRefreshBus.js'
|
|
|
|
/**
|
|
* 页面启用「从后台切回时自动刷新」能力
|
|
*
|
|
* 仅当 App 从后台切回前台时触发,不会因页面间普通跳转而触发。
|
|
* 由 App.vue 统一调度,页面只需关心自己的刷新逻辑。
|
|
*
|
|
* @param {Function} refreshFn 刷新逻辑(通常就是重新拉数据的函数)
|
|
*
|
|
* @example
|
|
* // 在 <script setup> 中:
|
|
* useBackgroundRefresh(() => {
|
|
* fetchList()
|
|
* })
|
|
*/
|
|
export function useBackgroundRefresh(refreshFn) {
|
|
if (typeof refreshFn !== 'function') {
|
|
throw new Error('useBackgroundRefresh: refreshFn must be a function')
|
|
}
|
|
|
|
let unregister = null
|
|
|
|
onMounted(() => {
|
|
unregister = onAppReturnFromBackground(refreshFn)
|
|
})
|
|
|
|
onBeforeUnmount(() => {
|
|
if (typeof unregister === 'function') unregister()
|
|
})
|
|
}
|