自定义渲染器 API {#custom-renderer-api}

createRenderer() {#createrenderer}

创建一个自定义渲染器。通过提供平台特定的节点创建以及更改 API,你可以在非 DOM 环境中也享受到 Vue 的核心运行时特性。

  • 类型

    1. function createRenderer<HostNode, HostElement>(
    2. options: RendererOptions<HostNode, HostElement>
    3. ): Renderer<HostElement>
    4. interface Renderer<HostElement> {
    5. render: RootRenderFunction<HostElement>
    6. createApp: CreateAppFunction<HostElement>
    7. }
    8. interface RendererOptions<HostNode, HostElement> {
    9. patchProp(
    10. el: HostElement,
    11. key: string,
    12. prevValue: any,
    13. nextValue: any,
    14. // the rest is unused for most custom renderers
    15. isSVG?: boolean,
    16. prevChildren?: VNode<HostNode, HostElement>[],
    17. parentComponent?: ComponentInternalInstance | null,
    18. parentSuspense?: SuspenseBoundary | null,
    19. unmountChildren?: UnmountChildrenFn
    20. ): void
    21. insert(
    22. el: HostNode,
    23. parent: HostElement,
    24. anchor?: HostNode | null
    25. ): void
    26. remove(el: HostNode): void
    27. createElement(
    28. type: string,
    29. isSVG?: boolean,
    30. isCustomizedBuiltIn?: string,
    31. vnodeProps?: (VNodeProps & { [key: string]: any }) | null
    32. ): HostElement
    33. createText(text: string): HostNode
    34. createComment(text: string): HostNode
    35. setText(node: HostNode, text: string): void
    36. setElementText(node: HostElement, text: string): void
    37. parentNode(node: HostNode): HostElement | null
    38. nextSibling(node: HostNode): HostNode | null
    39. // optional, DOM-specific
    40. querySelector?(selector: string): HostElement | null
    41. setScopeId?(el: HostElement, id: string): void
    42. cloneNode?(node: HostNode): HostNode
    43. insertStaticContent?(
    44. content: string,
    45. parent: HostElement,
    46. anchor: HostNode | null,
    47. isSVG: boolean
    48. ): [HostNode, HostNode]
    49. }
  • 示例

    1. import { createRenderer } from '@vue/runtime-core'
    2. const { render, createApp } = createRenderer({
    3. patchProp,
    4. insert,
    5. remove,
    6. createElement
    7. // ...
    8. })
    9. // `render` 是底层 API
    10. // `createApp` 返回一个应用实例
    11. export { render, createApp }
    12. // 重新导出 Vue 的核心 API
    13. export * from '@vue/runtime-core'

    Vue 自身的 @vue/runtime-dom 也是 利用同样这套 API 实现的。要想了解一个简单一些的实现,请看 @vue/runtime-test,这是一个 Vue 自己做单元测试的私有包。