Skip to content

Commit 04ac6c4

Browse files
underfinyyx990803
authored andcommitted
feat(runtime-core): support app.unmount(container) (#601)
close #593
1 parent 8ec69cb commit 04ac6c4

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

packages/runtime-core/__tests__/apiApp.spec.ts

+20
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,26 @@ describe('api: createApp', () => {
4646
expect(`already been mounted`).toHaveBeenWarned()
4747
})
4848

49+
test('unmount', () => {
50+
const Comp = {
51+
props: {
52+
count: {
53+
default: 0
54+
}
55+
},
56+
setup(props: { count: number }) {
57+
return () => props.count
58+
}
59+
}
60+
61+
const root = nodeOps.createElement('div')
62+
const app = createApp()
63+
app.mount(Comp, root)
64+
65+
app.unmount(root)
66+
expect(serializeInner(root)).toBe(``)
67+
})
68+
4969
test('provide', () => {
5070
const app = createApp()
5171
app.provide('foo', 1)

packages/runtime-core/src/apiCreateApp.ts

+5
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ export interface App<HostElement = any> {
2424
rootContainer: HostElement | string,
2525
rootProps?: Data
2626
): ComponentPublicInstance
27+
unmount(rootContainer: HostElement | string): void
2728
provide<T>(key: InjectionKey<T> | string, value: T): this
2829
}
2930

@@ -197,6 +198,10 @@ export function createAppAPI<HostNode, HostElement>(
197198
}
198199
},
199200

201+
unmount(rootContainer: HostElement) {
202+
render(null, rootContainer)
203+
},
204+
200205
provide(key, value) {
201206
if (__DEV__ && key in context.provides) {
202207
warn(

packages/runtime-dom/src/index.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export const createApp = (): App<Element> => {
2929
})
3030
}
3131

32-
const mount = app.mount
32+
const { mount, unmount } = app
3333
app.mount = (component, container, props): any => {
3434
if (isString(container)) {
3535
container = document.querySelector(container)!
@@ -52,6 +52,18 @@ export const createApp = (): App<Element> => {
5252
return mount(component, container, props)
5353
}
5454

55+
app.unmount = container => {
56+
if (isString(container)) {
57+
container = document.querySelector(container)!
58+
if (!container) {
59+
__DEV__ &&
60+
warn(`Failed to unmount app: mount target selector returned null.`)
61+
return
62+
}
63+
}
64+
unmount(container)
65+
}
66+
5567
return app
5668
}
5769

0 commit comments

Comments
 (0)