在 Vue 中集成 Univer
Vue 3+
集成前须知
- Univer 完全支持 Vue,你可以在 Vue 中使用 Univer 的所有功能。
- 你可能会用到
toRaw
方法来从响应式对象中获取原始对象。
集成步骤
- 在
onMounted
钩子中初始化 Univer - 在
onBeforeUnmount
钩子中销毁 Univer
示例代码
<template>
<div ref="container"></div>
</template>
<script setup>
import { onMounted, onBeforeUnmount, ref, toRaw } from 'vue'
import { createUniver, defaultTheme, LocaleType, merge } from '@univerjs/presets';
import { UniverSheetsCorePreset } from '@univerjs/presets/preset-sheets-core';
import UniverPresetSheetsCoreZhCN from '@univerjs/presets/preset-sheets-core/locales/zh-CN';
import '@univerjs/presets/lib/styles/preset-sheets-core.css';
const container = ref<HTMLElement | null>(null);
const univerAPIRef = ref<Univer | null>(null);
onMounted(() => {
const { univerAPI } = createUniver({
locale: LocaleType.ZH_CN,
locales: {
[LocaleType.ZH_CN]: merge(
{},
UniverPresetSheetsCoreZhCN,
),
},
theme: defaultTheme,
presets: [
UniverSheetsCorePreset({
container: container.value,
}),
],
});
univerAPI.createUniverSheet({ name: 'Test Sheet' });
univerAPIRef.value = univerAPI;
});
onBeforeUnmount(() => {
toRaw(univerRef.value)?.dispose();
univerAPIRef.value = null;
});
Vue 2.x
集成前须知
- 通常 Univer 会在 Vue 2.x 中正常工作,但是 Univer 的
ComponentManager
并不支持 Vue 2.x,因此你将无法将基于 Vue 2.x 编写的组件注册为 Univer 的自定义组件。 - 如果在开发环境中遇到了
ResizeObserver loop limit exceeded
警告,可以忽略它,也可以参考下面的代码片段解决:
if (process.env.NODE_ENV === 'development') {
const _ResizeObserver = window.ResizeObserver;
function debounce(fn, delay) {
let timer = null;
return function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
};
}
window.ResizeObserver = class ResizeObserver extends _ResizeObserver{
constructor(callback) {
callback = debounce(callback, 50);
super(callback)
}
}
}
集成步骤
- 在
mounted
钩子中初始化 Univer - 在
beforeDestroy
钩子中销毁 Univer
示例代码
<template>
<div ref="container"></div>
</template>
<script>
import { createUniver, defaultTheme, LocaleType, merge } from '@univerjs/presets';
import { UniverSheetsCorePreset } from '@univerjs/presets/preset-sheets-core';
import UniverPresetSheetsCoreZhCN from '@univerjs/presets/preset-sheets-core/locales/zh-CN';
import '@univerjs/presets/lib/styles/preset-sheets-core.css';
export default {
data() {
return {
univerAPI: null,
};
},
mounted() {
const { univerAPI } = createUniver({
locale: LocaleType.ZH_CN,
locales: {
[LocaleType.ZH_CN]: merge(
{},
UniverPresetSheetsCoreZhCN,
),
},
theme: defaultTheme,
presets: [
UniverSheetsCorePreset({
container: this.$refs.container,
}),
],
});
univerAPI.createUniverSheet({ name: 'Test Sheet' });
this.univerAPI = univerAPI;
},
beforeDestroy() {
this.univerAPI.dispose();
this.univerAPI = null;
},
}