12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- import { effectScope, onScopeDispose, watch } from 'vue'
- import { useIntervalFn } from '@vueuse/core'
- import uesFetch from '@/hooks/useFetch'
- import useMainStore from '@/store/main'
- import type { EffectScope, ShallowRef } from 'vue'
- import type { ExtractApiResponse } from 'api-type'
- const useMessageLoop = () => {
- const mainStore = useMainStore()
- const { fetch: getUnReadMessage, result: unReadMessage } = uesFetch('getUnReadMessage')
- watch(
- () => mainStore?.myUserInfo?.role,
- () => {
- if (mainStore?.myUserInfo?.role && mainStore?.myUserInfo?.role !== 'ADMIN') {
- getUnReadMessage()
- useIntervalFn(getUnReadMessage, 30 * 1000)
- }
- },
- {
- immediate: true,
- }
- )
- return unReadMessage
- }
- function createSharedComposable(composable: typeof useMessageLoop) {
- let subscribers = 0
- let state: ShallowRef<ExtractApiResponse<'getUnReadMessage'>> | null | undefined
- let scope: EffectScope | null
- const dispose = () => {
- if (scope && --subscribers <= 0) {
- scope.stop()
- state = scope = null
- }
- }
- return () => {
- subscribers++
- if (!state) {
- scope = effectScope(true)
- state = scope.run<ShallowRef<ExtractApiResponse<'getUnReadMessage'>>>(composable)
- }
- onScopeDispose(dispose)
- return state
- }
- }
- export default createSharedComposable(useMessageLoop)
|