背景
有时候在某些具体的业务需求场景中,我们需要动态的将VNode
或某个组件的示例挂载到页面中, 且无法预先在template
或者render
中部署组件时, 就需要有方法能够动态的创建组件的实例,并渲染到当前页面
代码
import { render as vueRender, createVNode } from 'vue'
class ComponentUtil {
/**
* 挂载VNode
* @param vNode
* @param options
*/
static mountVNode (vNode, options = {}) {
const { appContext } = options
const container = document.createDocumentFragment()
if (appContext) {
vNode.appContext = appContext
}
vueRender(vNode, container)
}
/**
* 挂载一个组件实例到document上
* @param component
* @param componentOptions
* @param children
* @param options
* @return {{dom?: HTMLElement, componentInstance?: Vue }}
*/
static mount (component, componentOptions = {}, children = undefined, options = {}) {
const m = this
const vNode = createVNode(component, componentOptions, children)
if (!vNode) {
return {}
}
m.mountVNode(vNode, options)
return {
dom: vNode?.el,
componentInstance: vNode?.component
}
}
}