Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(runtime-core): app.onUnmount() for registering cleanup functions (close: #4516) #4619

Merged
merged 8 commits into from
Apr 29, 2024
30 changes: 30 additions & 0 deletions packages/runtime-core/__tests__/apiCreateApp.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,36 @@ describe('api: createApp', () => {
).toHaveBeenWarnedTimes(1)
})

test.only('onUnmount', () => {
LinusBorg marked this conversation as resolved.
Show resolved Hide resolved
const cleanup = jest.fn().mockName('plugin cleanup')
const PluginA: Plugin = app => {
app.provide('foo', 1)
app.onUnmount(cleanup)
}
const PluginB: Plugin = {
install: (app, arg1, arg2) => {
app.provide('bar', arg1 + arg2)
app.onUnmount(cleanup)
}
}

const app = createApp({
render: () => `Test`
})
app.use(PluginA)
app.use(PluginB)

const root = nodeOps.createElement('div')
app.mount(root)

//also can be added after mount
app.onUnmount(cleanup)

app.unmount()

expect(cleanup).toHaveBeenCalledTimes(3)
})

test('config.errorHandler', () => {
const error = new Error()
const count = ref(0)
Expand Down
15 changes: 15 additions & 0 deletions packages/runtime-core/src/apiCreateApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export interface App<HostElement = any> {
isSVG?: boolean
): ComponentPublicInstance
unmount(): void
onUnmount(cb: () => void): void
provide<T>(key: InjectionKey<T> | string, value: T): this

// internal, but we need to expose these for the server-renderer and devtools
Expand Down Expand Up @@ -185,6 +186,7 @@ export function createAppAPI<HostElement>(

const context = createAppContext()
const installedPlugins = new Set()
const pluginCleanupFns: Array<() => any> = []

let isMounted = false

Expand Down Expand Up @@ -320,9 +322,22 @@ export function createAppAPI<HostElement>(
}
},

onUnmount(cleanupFn: () => void) {
if (typeof cleanupFn === 'function') pluginCleanupFns.push(cleanupFn)
LinusBorg marked this conversation as resolved.
Show resolved Hide resolved
else if (__DEV__) {
warn(
`Expected function as first argument to app.onUnmount(), but got ${typeof cleanupFn}`
)
}
},
LinusBorg marked this conversation as resolved.
Show resolved Hide resolved
unmount() {
if (isMounted) {
render(null, app._container)
pluginCleanupFns.map(fn => {
LinusBorg marked this conversation as resolved.
Show resolved Hide resolved
try {
fn()
} catch {}
})
if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
app._instance = null
devtoolsUnmountApp(app)
Expand Down