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) +}