自訂元件

Web SDK 提供了多種方式來整合自訂元件,使你能夠擴充並客製化 Web SDK 的功能。本指南將介紹幾種常用的方法。

Univer 的渲染函式不接受元件作為參數。需要先透過 Facade API 註冊元件,Univer 才能在各個掛載點找到它。

如果還沒有 Facade API 例項,請參閱 Facade API。

註冊自訂元件

TypeScript
univerAPI.registerComponent(componentKey, CustomComponent, options)

univerAPI.registerComponent 接受三個參數:

  • componentKey:元件的唯一標識,用於在 Univer 內引用該元件。
  • CustomComponent:元件本身,可以是 React 元件、Vue 元件或 Web Component。
  • options:可選配置,例如元件依賴的框架。

React 元件

React 元件不需要額外配置,只需確保它是一個有效的 React 元件:

TSX
function ReactComponent(props: Record<string, any>) {  return <div>Hello Univer!</div>}univerAPI.registerComponent('MyReactComponent', ReactComponent)

Vue 元件

Vue 3.x

註冊 Vue 元件前,需要先安裝並註冊 @univerjs/ui-adapter-vue3 包中的 UniverVue3AdapterPlugin:

Shell
pnpm add @univerjs/ui-adapter-vue3
TypeScript
import { UniverVue3AdapterPlugin } from '@univerjs/ui-adapter-vue3'univer.registerPlugin(UniverVue3AdapterPlugin)

註冊 Vue 元件時,將 framework 選項設定為 'vue3':

TSX
const Vue3Component = defineComponent({  setup(props) {    return () => <div>Hello Univer!</div>  },})univerAPI.registerComponent('MyVue3Component', Vue3Component, {  framework: 'vue3',})

Vue 2.x

Vue 2.x 已 EOL(End of Life),不再維護,因此 Univer 不提供 Vue 2.x 的 UI 介面卡外掛。可以透過自定義外掛實現,以下範例即是一個 Vue 2.x 介面卡:

TypeScript
import { DependentOn, Inject, Injector, Plugin } from '@univerjs/core'import { ComponentManager, UniverUIPlugin } from '@univerjs/ui'import Vue from 'vue'/** * 允許 Univer 使用 Vue 2 元件作為 UI 元件的插件。 */@DependentOn(UniverUIPlugin)export class UniverVue2AdapterPlugin extends Plugin {  static override pluginName = 'UNIVER_UI_VUE2_ADAPTER_PLUGIN'  constructor(    private readonly _config = {},    @Inject(Injector) protected readonly _injector: Injector,    @Inject(ComponentManager) protected readonly _componentManager: ComponentManager,  ) {    super()  }  override onStarting(): void {    const { createElement, useEffect, useRef } = this._componentManager.reactUtils    this._componentManager.setHandler('vue2', (component: any) => {      return (props: Record<string, any>) =>        createElement(VueComponentWrapper, {          component,          props: Object.keys(props).reduce<Record<string, any>>((acc, key) => {            if (key !== 'key') {              acc[key] = props[key]            }            return acc          }, {}),          reactUtils: { createElement, useEffect, useRef },        })    })  }}export function VueComponentWrapper(options: {  component: any  props: Record<string, any>  reactUtils: typeof ComponentManager.prototype.reactUtils}) {  const { component, props, reactUtils } = options  const { createElement, useEffect, useRef } = reactUtils  const domRef = useRef<HTMLDivElement>(null)  useEffect(() => {    if (!domRef.current) return    const Constructor = Vue.extend(component)    const instance = new Constructor({      data: props,    })    instance.$mount()    domRef.current.appendChild(instance.$el)    return () => {      instance.$destroy()    }  }, [props])  return createElement('div', { ref: domRef })}

然後註冊該外掛:

TypeScript
import { UniverVue2AdapterPlugin } from './ui-adapter-vue2'univer.registerPlugin(UniverUIPlugin)univer.registerPlugin(UniverVue2AdapterPlugin)

註冊 Vue 2.x 元件時,將 framework 選項設定為 'vue2':

TSX
const Vue2Component = Vue.component('MyVue2Component', {  template: '<div>Hello, Univer!</div>',})univerAPI.registerComponent('MyVue2Component', Vue2Component, {  framework: 'vue2',})

Web Components

Web Component 必須符合 Web Components 標準。請安裝並註冊 @univerjs/ui-adapter-web-component 包中的 UniverWebComponentAdapterPlugin:

Shell
pnpm add @univerjs/ui-adapter-web-component
TypeScript
import { UniverWebComponentAdapterPlugin } from '@univerjs/ui-adapter-web-component'univer.registerPlugin(UniverWebComponentAdapterPlugin)

註冊 Web Component 時,將 framework 選項設定為 'web-component':

TSX
class WebComponent extends HTMLElement {  constructor() {    super()    const shadow = this.attachShadow({ mode: 'open' })    const div = document.createElement('div')    div.textContent = 'Hello Univer!'    shadow.appendChild(div)  }}univerAPI.registerComponent('my-web-component', WebComponent, {  framework: 'web-component',})

使用自訂元件

以下方法可以將自定義元件掛載到 Univer 自身的介面中。

注意事項

  1. 呼叫這些方法前,請確保 Univer 已完成渲染。2. 元件需要先註冊再使用。3. 呼叫 dispose() 清理並移除新增的元件,否則會造成記憶體洩漏。

添加自訂選單項目

頂部選單欄(Ribbon)和右鍵選單(Context Menu)都可以放置自定義元件。這些選單項應由你的外掛提供,使用前註冊對應元件,並在外掛銷燬時一併釋放註冊。

替換內建元件

警告

替換內建元件可能導致部分功能無法正常工作。請先閱讀擬替換元件的原始碼和文件,再謹慎操作。

univerAPI.registerComponent 預設註冊覆蓋元件(override: true)。無論外掛在呼叫之前還是之後註冊內建預設元件,覆蓋元件都優先。每個 componentKey 同時只能有一個覆蓋元件,因此在註冊新的覆蓋元件前,應先釋放上一個註冊。對返回的註冊物件呼叫 dispose(),會恢復已註冊的內建預設元件。傳入 { override: false } 則註冊預設元件。

覆蓋元件應在對應檢視首次開啟前註冊。修改註冊不會重新渲染已掛載的檢視。

例如,以下程式碼替換內建的 ColorPicker 元件:

TSX
// 此程式碼僅可在 UI 層面替換內建 ColorPicker 元件,無法替代其功能實現univerAPI.registerComponent('UI_COLOR_PICKER_COMPONENT', () => <input type="color" />)

作為內容元件添加到……

在側邊欄中使用

univerAPI.openSidebar 會在 Univer 介面中開啟側邊欄,並在其中渲染自定義元件。

TSX
// 你應該在合適的時機(比如渲染完成)註冊元件univerAPI.registerComponent('MyCustomSidebarComponent', () => <div>Hello Univer!</div>)const sidebar = univerAPI.openSidebar({  header: { title: 'My Sidebar' },  children: { label: 'MyCustomSidebarComponent' },  onClose: () => {    console.log('close')  },  width: 360,})// 稍後關閉側邊欄sidebar.dispose()

參考:univerAPI.openSidebar

在對話框中使用

univerAPI.openDialog 會開啟一個渲染自定義元件的對話方塊。

TSX
// 你應該在合適的時機(比如渲染完成)註冊元件univerAPI.registerComponent('MyCustomDialogComponent', () => <div>Hello Univer!</div>)const dialog = univerAPI.openDialog({  id: 'unique-dialog-id', // 對話框的唯一識別符  draggable: true,  width: 300,  title: { title: 'My Dialog' },  children: {    label: 'MyCustomDialogComponent',  },  destroyOnClose: true,  preservePositionOnDestroy: true,  onClose: () => {},})// 稍後關閉對話框dialog.dispose()

參考:univerAPI.openDialog

你覺得這篇文檔如何?

© 2026 DreamNum Co., Ltd.