feat(vue): add composition API ionic lifecycle hooks (#22970)

resolves #22769
This commit is contained in:
Liam DeBeasi
2021-03-01 10:35:25 -05:00
committed by GitHub
parent 9486e51f6d
commit dd1c8dbf3b
6 changed files with 134 additions and 9 deletions

View File

@ -1,5 +1,12 @@
import { BackButtonEvent } from '@ionic/core';
import { inject, ref, Ref } from 'vue';
import {
inject,
ref,
Ref,
ComponentInternalInstance,
getCurrentInstance
} from 'vue';
import { LifecycleHooks } from './utils';
type Handler = (processNextHandler: () => void) => Promise<any> | void | null;
@ -62,3 +69,38 @@ export const useKeyboard = (): IonKeyboardRef => {
unregister
}
}
/**
* Creates an returns a function that
* can be used to provide a lifecycle hook.
*/
const injectHook = (lifecycleType: LifecycleHooks, hook: Function, component: ComponentInternalInstance | null): Function | undefined => {
if (component) {
// Add to public instance so it is accessible to IonRouterOutlet
const target = component as any;
const hooks = target.proxy[lifecycleType] || (target.proxy[lifecycleType] = []);
const wrappedHook = (...args: unknown[]) => {
if (target.isUnmounted) {
return;
}
return args ? hook(...args) : hook();
};
hooks.push(wrappedHook);
return wrappedHook;
} else {
console.warn('[@ionic/vue]: Ionic Lifecycle Hooks can only be used during execution of setup().');
}
}
const createHook = <T extends Function = () => any>(lifecycle: LifecycleHooks) => {
return (hook: T, target: ComponentInternalInstance | null = getCurrentInstance()) => injectHook(lifecycle, hook, target);
}
export const onIonViewWillEnter = createHook(LifecycleHooks.WillEnter);
export const onIonViewDidEnter = createHook(LifecycleHooks.DidEnter);
export const onIonViewWillLeave = createHook(LifecycleHooks.WillLeave);
export const onIonViewDidLeave = createHook(LifecycleHooks.DidLeave);