http://localhost:8080 作为示例地址)。# 创建新项目(已有项目可跳过)npm create vue@3 onlyoffice-vue3-democd onlyoffice-vue3-demo# 安装 ONLYOFFICE Vue 组件npm install --save @onlyoffice/document-editor-vue
二、完整可用组件示例(Composition API)
新建 src/components/OnlyOfficeEditor.vue:
<template><divstyle="width: 100%; height: 90vh; border: 1px solid #ccc;"><DocumentEditorid="docEditor":document-server-url="docServerUrl":config="editorConfig":on-load-component-error="onLoadError":events_onDocumentReady="onDocumentReady":events_onDocumentSave="onDocumentSave"/></div></template><scriptsetup>import { ref, reactive } from 'vue';import { DocumentEditor } from '@onlyoffice/document-editor-vue';// 👉 改成你的 Document Server 地址const docServerUrl = ref('http://localhost:8080');// 文档唯一 key(每次编辑/版本不同要变,否则会复用缓存)const docKey = ref('doc_' + Date.now());// 编辑器配置const editorConfig = reactive({width: '100%',height: '100%',documentType: 'word', // word/cell/slidedocument: {fileType: 'docx',key: docKey.value,title: '示例文档.docx',// 👉 你的文档下载地址(必须能被 Document Server 访问)url: 'http://localhost:8080/static/demo.docx'},editorConfig: {mode: 'edit', // edit 编辑 / view 只读lang: 'zh-CN',user: {id: 'user123',name: '测试用户'},// 👉 保存回调地址(后端接收保存请求)callbackUrl: 'http://localhost:3000/api/onlyoffice/callback'}});// 编辑器加载错误const onLoadError = (error) => {console.error('编辑器加载失败:', error);};// 文档加载完成const onDocumentReady = () => {console.log('文档加载完成,可以编辑了');};// 文档保存触发(由编辑器自动调用回调)const onDocumentSave = (event) => {console.log('编辑器触发保存,event:', event);};</script>
<template><divid="app"><h2>ONLYOFFICE Vue3 在线编辑示例</h2><OnlyOfficeEditor /></div></template><scriptsetup>import OnlyOfficeEditor from './components/OnlyOfficeEditor.vue';</script>
1. documentServerUrl
你的 ONLYOFFICE Document Server 地址,如:
http://192.168.1.100:8080https://your-doc-server.com
2. document.url(重要)
必须是能被 Document Server 直接下载的地址(不能是前端本地路径、不能带前端 Cookie 认证)。 示例:后端提供一个静态文件接口 /static/demo.docx。
3. editorConfig.mode
edit:可编辑(默认)view:只读预览
4. callbackUrl(保存 / 协同核心)
Document Server 编辑完成后,会 POST 到这个地址,把最终文件流发给你的后端。 后端拿到后覆盖保存即可。 五、后端回调(Node/Express 极简示例)
// server.jsconst express = require('express');const bodyParser = require('body-parser');const fs = require('fs');const app = express();app.use(bodyParser.json());app.post('/api/onlyoffice/callback', async (req, res) => {const { url } = req.body;if (!url) return res.status(400).send('no url');// 下载并保存文件const response = await fetch(url);const buffer = await response.arrayBuffer();fs.writeFileSync('./public/static/demo.docx', Buffer.from(buffer));res.json({ status: 'ok' });});app.listen(3000, () => console.log('callback server run on 3000'));
- 跨域:Document Server、前端、文件服务器要配置好 CORS。
- 文档打不开:
document.url必须能被 Document Server 独立访问。 - 保存无效:
callbackUrl必须是 公网 / 内网可访问 的后端接口。 - key 重复:每次新建 / 编辑不同文档,
document.key必须不同。
夜雨聆风