跳轉到內容
在本頁

自定義渲染器API

createRenderer()

建立一個自定義渲染器。透過提供平臺特定的節點建立和操作API,你可以利用Vue的核心執行時來針對非DOM環境。

  • 型別

    ts
    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 renderers
        isSVG?: boolean,
        prevChildren?: VNode<HostNode, HostElement>[],
        parentComponent?: ComponentInternalInstance | null,
        parentSuspense?: SuspenseBoundary | null,
        unmountChildren?: UnmountChildrenFn
      ): void
      insert(
        el: HostNode,
        parent: HostElement,
        anchor?: HostNode | null
      ): void
      remove(el: HostNode): void
      createElement(
        type: string,
        isSVG?: boolean,
        isCustomizedBuiltIn?: string,
        vnodeProps?: (VNodeProps & { [key: string]: any }) | null
      ): HostElement
      createText(text: string): HostNode
      createComment(text: string): HostNode
      setText(node: HostNode, text: string): void
      setElementText(node: HostElement, text: string): void
      parentNode(node: HostNode): HostElement | null
      nextSibling(node: HostNode): HostNode | null
    
      // optional, DOM-specific
      querySelector?(selector: string): HostElement | null
      setScopeId?(el: HostElement, id: string): void
      cloneNode?(node: HostNode): HostNode
      insertStaticContent?(
        content: string,
        parent: HostElement,
        anchor: HostNode | null,
        isSVG: boolean
      ): [HostNode, HostNode]
    }
  • 示例

    js
    import { createRenderer } from '@vue/runtime-core'
    
    const { render, createApp } = createRenderer({
      patchProp,
      insert,
      remove,
      createElement
      // ...
    })
    
    // `render` is the low-level API
    // `createApp` returns an app instance
    export { render, createApp }
    
    // re-export Vue core APIs
    export * from '@vue/runtime-core'

    Vue自帶的 @vue/runtime-dom 是使用相同的API實現的。[檢視實現](https://github.com/vuejs/core/blob/main/packages/runtime-dom/src/index.ts)。對於更簡單的實現,請檢視[@vue/runtime-test](https://github.com/vuejs/core/blob/main/packages/runtime-test/src/index.ts),這是Vue內部單元測試的私有包。

自定義渲染器 API 已載入