dynamicMount
动态挂载 Vue 组件到 DOM 容器中,支持更新和销毁操作。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
options.createVNode | typeof createVNode | Vue 创建 VNode 函数 |
options.render | typeof render | Vue 渲染函数 |
options.createElement | Document['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']
}参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
Comp | Component | 是 | Vue 组件 |
options.props | Record<string, any> | 是 | 组件属性 |
options.container | HTMLElement | 是 | 挂载容器元素 |
options.appContext | AppContext | 是 | Vue 应用上下文 |
options.createVNode | typeof createVNode | 是 | Vue 创建 VNode 函数 |
options.render | typeof render | 是 | Vue 渲染函数 |
options.createElement | Document['createElement'] | 是 | 创建 DOM 元素函数 |
返回值
| 类型 | 说明 |
|---|---|
{ vnode, update, destroy, el } | 返回对象,包含 VNode、更新函数、销毁函数和容器元素 |
工作原理
- 创建容器:在指定的容器中创建一个 div 元素作为组件挂载点
- 创建VNode:使用
createVNode创建组件 VNode,设置应用上下文 - 渲染组件:使用
render将 VNode 渲染到容器元素中 - 返回控制对象:
vnode: 创建的 VNode 实例update: 更新组件属性的函数destroy: 销毁组件并移除 DOM 的函数el: 容器元素引用
适用于动态创建和挂载 Vue 组件的场景,如弹窗、提示框等。