feat: preserving state between route changes (#132)

This commit is contained in:
Ayaka Rizumu 2022-11-28 01:34:45 +08:00 committed by GitHub
parent d967520005
commit 6414f2a4e2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 63 additions and 10 deletions

30
composables/lifecycle.ts Normal file
View file

@ -0,0 +1,30 @@
import type { ComponentInternalInstance } from 'vue'
import { onActivated, onDeactivated, ref } from 'vue'
/**
* ### Whether the current component is running in the background
*
* for handling problems caused by the keepalive function
*/
export function useDeactivated() {
const deactivated = ref(false)
onActivated(() => deactivated.value = false)
onDeactivated(() => deactivated.value = true)
return deactivated
}
/**
* ### When the component is restored from the background
*
* for handling problems caused by the keepalive function
*/
export function onReactivated(hook: Function, target?: ComponentInternalInstance | null): void {
const initial = ref(true)
onActivated(() => {
if (initial.value)
return
hook()
}, target)
onDeactivated(() => initial.value = false)
}

View file

@ -1,4 +1,5 @@
import type { Paginator } from 'masto'
import { useDeactivated } from './lifecycle'
import type { PaginatorState } from '~/types'
export function usePaginator<T>(paginator: Paginator<any, T[]>) {
@ -10,6 +11,7 @@ export function usePaginator<T>(paginator: Paginator<any, T[]>) {
const bound = reactive(useElementBounding(endAnchor))
const isInScreen = $computed(() => bound.top < window.innerHeight * 2)
const error = ref<unknown | undefined>()
const deactivated = useDeactivated()
async function loadNext() {
if (state.value !== 'idle')
@ -44,7 +46,12 @@ export function usePaginator<T>(paginator: Paginator<any, T[]>) {
watch(
() => isInScreen,
() => {
if (isInScreen && state.value === 'idle')
if (
isInScreen
&& state.value === 'idle'
// No new content is loaded when the keepAlive page enters the background
&& deactivated.value === false
)
loadNext()
},
{ immediate: true },