From f01a53f834bff7aa8620d9ef46f5e6473e2a2ff4 Mon Sep 17 00:00:00 2001 From: haoziqaq <357229046@qq.com> Date: Fri, 18 Feb 2022 14:41:29 +0800 Subject: [PATCH] refactor: add mount component method --- .../varlet-vue2-ui/src/utils/components.ts | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/packages/varlet-vue2-ui/src/utils/components.ts b/packages/varlet-vue2-ui/src/utils/components.ts index e385b45..3f38e53 100644 --- a/packages/varlet-vue2-ui/src/utils/components.ts +++ b/packages/varlet-vue2-ui/src/utils/components.ts @@ -1,3 +1,6 @@ +import Vue, { ComponentOptions } from 'vue' +import { CombinedVueInstance } from 'vue/types/vue' + export function pickProps(props: T, propsKey: U): T[U] export function pickProps(props: T, propsKey: U[]): Pick export function pickProps(props: any, propsKey: any): any { @@ -8,3 +11,23 @@ export function pickProps(props: any, propsKey: any): any { }, {}) : props[propsKey] } + +export interface MountComponentApi { + instance: CombinedVueInstance; + unmount(): void; +} + +export function mountComponent(component: ComponentOptions, container: string, options = {}): MountComponentApi { + const instance = new (Vue.extend(component))(options) + const el = instance.$mount().$el + const wrapper = document.querySelector(container)! + wrapper.appendChild(el) + + return { + instance, + unmount() { + instance.$destroy() + wrapper.removeChild(el) + }, + } +}