gaoluyang
2 天以前 b871888a4ee32d15adfd52fdfabc44c7c674db0e
src/components/Onlyoffice/onlyoffice.vue
@@ -4,6 +4,37 @@
</template>
<script>
// OnlyOffice 文档服务地址,按环境配置;脚本在真正需要预览时才加载
const OFFICE_API_BASE = process.env.VUE_APP_ONLYOFFICE_API || "http://192.168.21.53:9001";
// 多个页面共用编辑器,api.js 只加载一次
let docsApiPromise = null;
function loadDocsApi() {
  if (window.DocsAPI) {
    return Promise.resolve(window.DocsAPI);
  }
  if (!docsApiPromise) {
    docsApiPromise = new Promise((resolve, reject) => {
      const script = document.createElement("script");
      script.src = OFFICE_API_BASE.replace(/\/$/, "") + "/web-apps/apps/api/documents/api.js";
      script.onload = () => {
        if (window.DocsAPI) {
          resolve(window.DocsAPI);
        } else {
          reject(new Error("api.js 加载完成但未注册 DocsAPI"));
        }
      };
      script.onerror = () => reject(new Error("OnlyOffice 文档服务脚本加载失败:" + script.src));
      document.head.appendChild(script);
    });
    // 加载失败后允许下次重试
    docsApiPromise.catch(() => {
      docsApiPromise = null;
    });
  }
  return docsApiPromise;
}
export default {
  name: "VabOnlyOffice",
  props: ['options'],
@@ -50,10 +81,7 @@
    }
  },
  beforeDestroy() {
    if (this.docEditor !== null) {
      this.docEditor.destroyEditor();
      this.docEditor = null;
    }
    this.destroyEditor();
  },
  watch: {
    option: {
@@ -70,10 +98,17 @@
    }
  },
  methods: {
    async setEditor(option) {
    destroyEditor() {
      if (this.docEditor !== null) {
        this.docEditor.destroyEditor();
        this.docEditor = null;
      }
    },
    async setEditor(option) {
      this.destroyEditor();
      // 没有文档地址就不初始化编辑器,避免访问尚未加载的 DocsAPI
      if (!option || !option.url) {
        return;
      }
      this.doctype = this.getFileType(option.fileType);
      let config = {
@@ -116,8 +151,17 @@
        token: option.token || ""
      };
      // eslint-disable-next-line no-undef,no-unused-vars
      this.docEditor = new DocsAPI.DocEditor("vabOnlyOffice", config);
      try {
        await loadDocsApi();
      } catch (error) {
        console.error(error);
        this.$message.error("文档服务暂时不可用,无法预览");
        return;
      }
      if (this._isDestroyed) {
        return;
      }
      this.docEditor = new window.DocsAPI.DocEditor("vabOnlyOffice", config);
    },
    getFileType(fileType) {
      let docType = "";