自定义渲染器 API {#custom-renderer-api}
createRenderer() {#createrenderer}
创建一个自定义渲染器。通过提供平台特定的节点创建以及更改 API,你可以在非 DOM 环境中也享受到 Vue 的核心运行时特性。
类型
function createRenderer<HostNode, HostElement>(options: RendererOptions<HostNode, HostElement>): Renderer<HostElement>interface Renderer<HostElement> {render: RootRenderFunction<HostElement>createApp: CreateAppFunction<HostElement>}interface RendererOptions<HostNode, HostElement> {patchProp(el: HostElement,key: string,prevValue: any,nextValue: any,// the rest is unused for most custom renderersisSVG?: boolean,prevChildren?: VNode<HostNode, HostElement>[],parentComponent?: ComponentInternalInstance | null,parentSuspense?: SuspenseBoundary | null,unmountChildren?: UnmountChildrenFn): voidinsert(el: HostNode,parent: HostElement,anchor?: HostNode | null): voidremove(el: HostNode): voidcreateElement(type: string,isSVG?: boolean,isCustomizedBuiltIn?: string,vnodeProps?: (VNodeProps & { [key: string]: any }) | null): HostElementcreateText(text: string): HostNodecreateComment(text: string): HostNodesetText(node: HostNode, text: string): voidsetElementText(node: HostElement, text: string): voidparentNode(node: HostNode): HostElement | nullnextSibling(node: HostNode): HostNode | null// optional, DOM-specificquerySelector?(selector: string): HostElement | nullsetScopeId?(el: HostElement, id: string): voidcloneNode?(node: HostNode): HostNodeinsertStaticContent?(content: string,parent: HostElement,anchor: HostNode | null,isSVG: boolean): [HostNode, HostNode]}
示例
import { createRenderer } from '@vue/runtime-core'const { render, createApp } = createRenderer({patchProp,insert,remove,createElement// ...})// `render` 是底层 API// `createApp` 返回一个应用实例export { render, createApp }// 重新导出 Vue 的核心 APIexport * from '@vue/runtime-core'
Vue 自身的
@vue/runtime-dom也是 利用同样这套 API 实现的。要想了解一个简单一些的实现,请看@vue/runtime-test,这是一个 Vue 自己做单元测试的私有包。
