自定义组件
Web SDK 提供了多种方式来集成自定义组件,使你能够扩展和定制 Web SDK 的功能。本指南将介绍几种常用的方法。
Univer 的渲染调用不接受组件作为参数。组件必须先通过 Facade API 注册,之后才能在 Univer 挂载组件的位置引用。
如果还没有 Facade API 实例,参见 Facade API。
注册自定义组件
univerAPI.registerComponent(componentKey, CustomComponent, options)univerAPI.registerComponent 用于注册组件,接受三个参数:
componentKey:组件的唯一标识,Univer 内部通过它引用组件。CustomComponent:组件本身,可以是 React 组件、Vue 组件或 Web Component。options:可选配置,用于指定组件依赖的框架或其他相关设置。
React 组件
React 组件无需额外配置,组件本身是合法的 React 组件即可:
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:
pnpm add @univerjs/ui-adapter-vue3npm install @univerjs/ui-adapter-vue3yarn add @univerjs/ui-adapter-vue3bun add @univerjs/ui-adapter-vue3import { UniverVue3AdapterPlugin } from '@univerjs/ui-adapter-vue3'univer.registerPlugin(UniverVue3AdapterPlugin)注册组件时将 framework 指定为 'vue3':
const Vue3Component = defineComponent({ setup(props) { return () => <div>Hello Univer!</div> },})univerAPI.registerComponent('MyVue3Component', Vue3Component, { framework: 'vue3',})Vue 2.x
Vue 2.x 已停止维护,Univer 目前未提供 Vue 2.x 的 UI 适配器插件。可以编写自定义插件完成适配,下面的代码可作为参考:
import { DependentOn, Inject, Injector, Plugin } from '@univerjs/core'import { ComponentManager, UniverUIPlugin } from '@univerjs/ui'import Vue from 'vue'/** * The plugin that allows Univer to use Vue 2 components as UI components. */@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 })}然后注册插件:
import { UniverVue2AdapterPlugin } from './ui-adapter-vue2'univer.registerPlugin(UniverUIPlugin)univer.registerPlugin(UniverVue2AdapterPlugin)注册 Vue 2.x 组件时,将 framework 指定为 'vue2':
const Vue2Component = Vue.component('MyVue2Component', { template: '<div>Hello, Univer!</div>',})univerAPI.registerComponent('MyVue2Component', Vue2Component, { framework: 'vue2',})Web Components
注册 Web Components 时,组件本身必须符合 Web Components 标准。先安装 @univerjs/ui-adapter-web-component,再注册该包中的 UniverWebComponentAdapterPlugin:
pnpm add @univerjs/ui-adapter-web-componentnpm install @univerjs/ui-adapter-web-componentyarn add @univerjs/ui-adapter-web-componentbun add @univerjs/ui-adapter-web-componentimport { UniverWebComponentAdapterPlugin } from '@univerjs/ui-adapter-web-component'univer.registerPlugin(UniverWebComponentAdapterPlugin)注册组件时将 framework 指定为 'web-component':
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',})Angular
@angular/elements 的 createCustomElement 将 Angular 组件包装为自定义元素。用 Univer 的 Web Component 适配器注册该元素后,Angular 组件即可显示在 Univer 的侧边栏或对话框中。
@angular/elements 的版本需与 @angular/core 一致,@univerjs/ui-adapter-web-component 的版本需与其他 Univer 包一致。
在 Univer 初始化之后调用该函数。注入器由宿主组件传入:宿主组件用 private readonly injector = inject(Injector) 获取注入器,然后调用 registerAngularPanel(univer, univerAPI, this.injector)。宿主组件中的 inject 和 Injector 均从 @angular/core 导入。
import type { Injector } from '@angular/core'import type { FUniver, Univer } from '@univerjs/presets'import { Component } from '@angular/core'import { createCustomElement } from '@angular/elements'import { UniverWebComponentAdapterPlugin } from '@univerjs/ui-adapter-web-component'@Component({ selector: 'app-angular-panel', standalone: true, template: '<p>Hello from Angular!</p>',})export class AngularPanelComponent {}export function registerAngularPanel(univer: Univer, univerAPI: FUniver, injector: Injector) { const element = createCustomElement(AngularPanelComponent, { injector }) univer.registerPlugin(UniverWebComponentAdapterPlugin) return univerAPI.registerComponent('univer-angular-panel', element, { framework: 'web-component', })}编辑器渲染完成后,把注册时的 key 作为侧边栏内容:
const sidebar = univerAPI.openSidebar({ header: { title: 'Angular' }, children: { label: 'univer-angular-panel' }, width: 360,})保留注册句柄和侧边栏句柄,不再需要时分别调用 dispose()。自定义元素在每个应用中只需注册一次,名称必须包含连字符,并且不能与 Angular 组件的 selector 相同。
Angular Elements 将输入映射为元素属性,将输出映射为 DOM 的 CustomEvent 事件。Univer 的适配器会设置这些属性,但不会自动订阅 Angular 的输出,需要时由应用自行桥接这些事件。
使用自定义组件
以下方法用于将自定义组件放入 Univer 渲染的位置,从而扩展和定制界面。
注意事项
- 确认 Univer 已完成渲染后再调用这些方法。
- 使用组件前先完成注册。
- 使用
dispose()清理添加的内容,避免内存泄漏。
添加自定义菜单项
顶部菜单栏(Ribbon)和右键菜单(Context Menu)都可以承载自定义组件。菜单项由插件注册,因此新增菜单项需要编写自定义插件。新增自定义菜单项的最佳实践可以作为起点。
替换内置组件
警告
替换内置组件可能导致依赖该组件的功能失效。替换前请阅读源码和文档,确认哪些组件可以替换,并谨慎操作。
univerAPI.registerComponent 默认注册覆盖组件(override: true)。无论插件在调用之前还是之后注册内置默认组件,覆盖组件都优先。每个 componentKey 同时只能有一个生效的覆盖组件,因此再次注册前需先释放上一个注册。对返回值调用 dispose() 可以恢复已注册的内置默认组件。传入 { override: false } 则注册默认组件。
覆盖组件需要在对应视图第一次打开之前完成注册。注册发生变化不会让已经挂载的视图自动重新渲染。
Sheets 从包的公共入口导出以下标识,覆盖对应的内置组件时使用这些标识:
| 组件 | 导出的标识 | 包 |
|---|---|---|
| 定义名称 | DEFINED_NAME_CONTAINER | @univerjs/sheets-ui |
| 更多函数 | MORE_FUNCTIONS_COMPONENT | @univerjs/sheets-formula-ui |
| 数据验证 | DATA_VALIDATION_PANEL | @univerjs/sheets-data-validation-ui |
| 条件格式 | CF_PANEL_KEY | @univerjs/sheets-conditional-formatting-ui |
例如,以下代码替换内置的 ColorPicker 组件:
// 此代码仅可在 UI 层面替换内置 ColorPicker 组件,无法替代其功能实现univerAPI.registerComponent('UI_COLOR_PICKER_COMPONENT', () => <input type="color" />)作为内容组件添加到……
在侧边栏中使用
univerAPI.openSidebar 在 Univer 界面中打开侧边栏,并在其中渲染已注册的组件。
// 你应该在合适的时机(比如渲染完成)注册组件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.openDialog 打开对话框,并在其中渲染已注册的组件。
// 你应该在合适的时机(比如渲染完成)注册组件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()将弹出框附加到单元格
FRange.attachPopup 将自定义弹出框附加到指定的单元格范围。
- Popup 是依附在单元格上的临时 DOM 元素,通常用于显示临时状态信息,不支持持久化存储。
- 方法签名是
FRange.attachPopup(popup: IFCanvasPopup)。 - Popup 附着在单元格的四边,被遮挡时会自动调整位置和方向。
// 你应该在合适的时机(比如渲染完成)注册组件univerAPI.registerComponent( 'MyCustomPopupComponent', () => <div>Hello Univer!</div>,)const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:J10')// 将弹出窗口附加到范围的第一个单元格// 如果 `disposable` 为 null,则表示 popup 添加失败const disposable = fRange.attachPopup({ componentKey: 'MyCustomPopupComponent',})// 移除弹出框disposable.dispose()附加警告弹出框
FRange.attachAlertPopup 在指定范围的起始单元格上附加警告弹出框。
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')const disposable = fRange.attachAlertPopup({ key: 'unique-alert-key', // 唯一标识符 title: '这是一个警告!', message: '这是一个警告!', width: 300, height: 200, // 0: 信息 // 1: 警告 // 2: 错误 type: 0,})// 稍后移除警告disposable.dispose()添加浮动 DOM 到工作表
FWorksheet.addFloatDomToPosition 在工作表中添加浮动 DOM 元素。
- 使用前需要安装
@univerjs/sheets-drawing-ui插件或@univerjs/preset-sheets-drawing预设。 - 浮动 DOM 元素是悬浮在工作表上、可以拖动的组件,支持持久化存储。
- 需要在 Univer 渲染完成后调用。
componentKey:组件的唯一标识,Univer 内部通过它引用组件。- 完整的参数定义
// 你应该在合适的时机(比如渲染完成)注册组件univerAPI.registerComponent( 'MyCustomFloatingDOMComponent', ({ data }) => ( <div> Hello {data?.label} ! </div> ),)const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// 添加一个浮动 DOM// 如果 `disposable` 为 null,则表示浮动 DOM 添加失败const disposable = fWorksheet.addFloatDomToPosition({ componentKey: 'MyCustomFloatingDOMComponent', initPosition: { startX: 100, endX: 200, startY: 100, endY: 200, }, // 这是组件的数据 data: { label: 'Univer', },})// 移除浮动 DOMdisposable.dispose()你觉得这篇文档如何?