From f573b95c801bfb05ebbeb268d9f9e77e527f9945 Mon Sep 17 00:00:00 2001 From: Ngheizit <73107765+xizher@users.noreply.github.com> Date: Fri, 3 Sep 2021 04:00:38 +0800 Subject: [PATCH] feat(tryOnBeforeUnmount): new function (#709) --- packages/shared/index.ts | 1 + packages/shared/tryOnBeforeUnmount/index.md | 37 +++++++++++++++++++++ packages/shared/tryOnBeforeUnmount/index.ts | 12 +++++++ 3 files changed, 50 insertions(+) create mode 100644 packages/shared/tryOnBeforeUnmount/index.md create mode 100644 packages/shared/tryOnBeforeUnmount/index.ts diff --git a/packages/shared/index.ts b/packages/shared/index.ts index 232e04c6b5c6..9ee347539817 100644 --- a/packages/shared/index.ts +++ b/packages/shared/index.ts @@ -21,6 +21,7 @@ export * from './syncRef' export * from './throttledWatch' export * from './toReactive' export * from './toRefs' +export * from './tryOnBeforeUnmount' export * from './tryOnMounted' export * from './tryOnScopeDispose' export * from './tryOnUnmounted' diff --git a/packages/shared/tryOnBeforeUnmount/index.md b/packages/shared/tryOnBeforeUnmount/index.md new file mode 100644 index 000000000000..1f4b6b411a6d --- /dev/null +++ b/packages/shared/tryOnBeforeUnmount/index.md @@ -0,0 +1,37 @@ +--- +category: Component +--- + +# tryOnUnmounted + +Safe `onBeforeUnmount`. Call `onBeforeUnmount()` if it's inside a component lifecycle, if not, do nothing + +## Usage + +```js +import { tryOnBeforeUnmount } from '@vueuse/core' + +tryOnBeforeUnmount(() => { + +}) +``` + + + +## Type Declarations + +```typescript +/** + * Call onUnmounted() if it's inside a component lifecycle, if not, do nothing + * + * @param fn + */ +export declare function tryOnBeforeUnmount(fn: Fn): void +``` + +## Source + +[Source](https://github.com/vueuse/vueuse/blob/main/packages/shared/tryOnBeforeUnmount/index.ts) • [Docs](https://github.com/vueuse/vueuse/blob/main/packages/shared/tryOnBeforeUnmount/index.md) + + + diff --git a/packages/shared/tryOnBeforeUnmount/index.ts b/packages/shared/tryOnBeforeUnmount/index.ts new file mode 100644 index 000000000000..e7b223327369 --- /dev/null +++ b/packages/shared/tryOnBeforeUnmount/index.ts @@ -0,0 +1,12 @@ +import { getCurrentInstance, onBeforeUnmount } from 'vue-demi' +import { Fn } from '../utils' + +/** + * Call onBeforeUnmount() if it's inside a component lifecycle, if not, do nothing + * + * @param fn + */ +export function tryOnBeforeUnmount(fn: Fn) { + if (getCurrentInstance()) + onBeforeUnmount(fn) +}