Skip to content

dynamicMount

动态挂载 Vue 组件到 DOM 容器中,支持更新和销毁操作。

前置依赖

依赖参数

参数名类型说明
options.createVNodetypeof createVNodeVue 创建 VNode 函数
options.rendertypeof renderVue 渲染函数
options.createElementDocument['createElement']创建 DOM 元素函数

环境要求

  • vue: Vue 3.x 运行时
  • 浏览器环境: 依赖 DOM API
bash
npm install vue

函数签名

typescript
function dynamicMount(
  Comp: Component,
  options: DynamicMountOptions
): { vnode: VNode | null; update: (props: Record<string, any>) => void; destroy: () => void; el: HTMLElement }

interface DynamicMountOptions {
  props: Record<string, any>
  container: HTMLElement
  appContext: AppContext
  createVNode: typeof createVNode
  render: typeof render
  createElement: Document['createElement']
}

参数

参数名类型必填说明
CompComponentVue 组件
options.propsRecord<string, any>组件属性
options.containerHTMLElement挂载容器元素
options.appContextAppContextVue 应用上下文
options.createVNodetypeof createVNodeVue 创建 VNode 函数
options.rendertypeof renderVue 渲染函数
options.createElementDocument['createElement']创建 DOM 元素函数

返回值

类型说明
{ vnode, update, destroy, el }返回对象,包含 VNode、更新函数、销毁函数和容器元素

工作原理

  1. 创建容器:在指定的容器中创建一个 div 元素作为组件挂载点
  2. 创建VNode:使用 createVNode 创建组件 VNode,设置应用上下文
  3. 渲染组件:使用 render 将 VNode 渲染到容器元素中
  4. 返回控制对象
    • vnode: 创建的 VNode 实例
    • update: 更新组件属性的函数
    • destroy: 销毁组件并移除 DOM 的函数
    • el: 容器元素引用

适用于动态创建和挂载 Vue 组件的场景,如弹窗、提示框等。