index.vue 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. <template>
  2. <div class="wps-editor-container">
  3. <div v-if="loading" class="loading-container">
  4. <el-icon class="is-loading"><Loading /></el-icon>
  5. <span>正在加载 WPS 编辑器...</span>
  6. </div>
  7. <div v-if="error" class="error-container">
  8. <el-alert type="error" title="加载失败" :closable="false">
  9. <div style="white-space: pre-line; line-height: 1.6">{{ error }}</div>
  10. </el-alert>
  11. </div>
  12. <div ref="wpsContainerRef" class="wps-container"></div>
  13. </div>
  14. </template>
  15. <script setup lang="ts">
  16. import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
  17. import { Loading } from '@element-plus/icons-vue';
  18. import { ElMessage } from 'element-plus';
  19. interface Props {
  20. fileUrl: string;
  21. fileName?: string;
  22. fileType?: 'doc' | 'docx' | 'xls' | 'xlsx' | 'ppt' | 'pptx' | 'pdf';
  23. mode?: 'simple' | 'normal';
  24. userId?: string;
  25. userName?: string;
  26. enableComment?: boolean;
  27. enableRevision?: boolean;
  28. enableWatermark?: boolean;
  29. watermarkText?: string;
  30. enableDownload?: boolean;
  31. enablePrint?: boolean;
  32. enableCopy?: boolean;
  33. enableSave?: boolean;
  34. enableShare?: boolean;
  35. enableHistory?: boolean;
  36. readOnly?: boolean;
  37. }
  38. interface Emits {
  39. (e: 'ready'): void;
  40. (e: 'error', error: string): void;
  41. (e: 'save', data: any): void;
  42. (e: 'fileChange', data: any): void;
  43. }
  44. const props = withDefaults(defineProps<Props>(), {
  45. mode: 'normal',
  46. fileName: '未命名文档',
  47. userId: 'user_' + Date.now(),
  48. userName: '当前用户',
  49. enableComment: true,
  50. enableRevision: true,
  51. enableWatermark: false,
  52. watermarkText: '',
  53. enableDownload: true,
  54. enablePrint: true,
  55. enableCopy: true,
  56. enableSave: true,
  57. enableShare: false,
  58. enableHistory: false,
  59. readOnly: false
  60. });
  61. const emit = defineEmits<Emits>();
  62. const wpsContainerRef = ref<HTMLDivElement>();
  63. const loading = ref(true);
  64. const error = ref('');
  65. let wpsInstance: any = null;
  66. // WPS 配置
  67. const WPS_APP_ID = 'SX20251229FLIAPDAPP';
  68. // 初始化 WPS 编辑器(符合官方文档)
  69. const initWpsEditor = async () => {
  70. if (!wpsContainerRef.value || !props.fileUrl) {
  71. error.value = '缺少必要参数';
  72. loading.value = false;
  73. emit('error', error.value);
  74. return;
  75. }
  76. try {
  77. loading.value = true;
  78. error.value = '';
  79. // 检查 WPS SDK 是否已加载
  80. if (!(window as any).WebOfficeSDK) {
  81. const errorMsg =
  82. 'WPS SDK 未加载。请按以下步骤操作:\n\n1. 从 WPS 官网下载 JSSDK\n2. 将 SDK 文件放到 public 目录\n3. 在 index.html 中引入 SDK 脚本\n\n或使用 CDN(需要网络连接)';
  83. error.value = errorMsg;
  84. loading.value = false;
  85. emit('error', errorMsg);
  86. return;
  87. }
  88. const WebOfficeSDK = (window as any).WebOfficeSDK;
  89. // 根据文件类型确定 officeType
  90. let officeType = WebOfficeSDK.OfficeType.Writer;
  91. if (props.fileType === 'xlsx' || props.fileType === 'xls') {
  92. officeType = WebOfficeSDK.OfficeType.Spreadsheet;
  93. } else if (props.fileType === 'pptx' || props.fileType === 'ppt') {
  94. officeType = WebOfficeSDK.OfficeType.Presentation;
  95. } else if (props.fileType === 'pdf') {
  96. officeType = WebOfficeSDK.OfficeType.Pdf;
  97. }
  98. // 生成唯一的文件ID
  99. const fileId = `${props.userId}_${Date.now()}`;
  100. // 构建初始化配置(符合官方文档)
  101. const config: any = {
  102. // 必需参数
  103. appId: WPS_APP_ID,
  104. officeType: officeType,
  105. fileId: fileId,
  106. // 挂载节点
  107. mount: wpsContainerRef.value,
  108. // 自定义参数(会传递到回调接口)
  109. customArgs: {
  110. fileName: props.fileName,
  111. fileUrl: props.fileUrl,
  112. userId: props.userId,
  113. userName: props.userName,
  114. readOnly: props.readOnly,
  115. enableComment: props.enableComment,
  116. enableRevision: props.enableRevision
  117. }
  118. };
  119. console.log('[WPS] 初始化配置:', config);
  120. // 初始化 WebOffice
  121. wpsInstance = await WebOfficeSDK.init(config);
  122. loading.value = false;
  123. emit('ready');
  124. console.log('[WPS] 编辑器初始化成功');
  125. } catch (err: any) {
  126. console.error('[WPS] 初始化失败:', err);
  127. error.value = err.message || '初始化失败';
  128. loading.value = false;
  129. emit('error', error.value);
  130. }
  131. };
  132. // 保存文档
  133. const saveDocument = async () => {
  134. if (!wpsInstance) {
  135. ElMessage.warning('编辑器未初始化');
  136. return null;
  137. }
  138. try {
  139. console.log('[WPS] 开始保存文档');
  140. // 调用 WPS 的保存方法
  141. const result = await wpsInstance.save();
  142. console.log('[WPS] 保存成功:', result);
  143. ElMessage.success('保存成功');
  144. emit('save', result);
  145. return result;
  146. } catch (err: any) {
  147. console.error('[WPS] 保存失败:', err);
  148. ElMessage.error('保存失败');
  149. throw err;
  150. }
  151. };
  152. // 销毁编辑器
  153. const destroyEditor = () => {
  154. if (wpsInstance) {
  155. try {
  156. if (wpsInstance.destroy) {
  157. wpsInstance.destroy();
  158. }
  159. wpsInstance = null;
  160. console.log('[WPS] 编辑器已销毁');
  161. } catch (err) {
  162. console.error('[WPS] 销毁编辑器失败:', err);
  163. }
  164. }
  165. };
  166. // 监听文件 URL 变化
  167. watch(
  168. () => props.fileUrl,
  169. (newUrl) => {
  170. if (newUrl) {
  171. destroyEditor();
  172. initWpsEditor();
  173. }
  174. }
  175. );
  176. onMounted(() => {
  177. // 等待 WPS SDK 加载完成
  178. let checkCount = 0;
  179. const maxChecks = 100; // 10秒超时(100 * 100ms)
  180. const checkWpsSDK = setInterval(() => {
  181. checkCount++;
  182. if ((window as any).WebOfficeSDK) {
  183. clearInterval(checkWpsSDK);
  184. console.log('[WPS] SDK 加载成功');
  185. if (props.fileUrl) {
  186. initWpsEditor();
  187. }
  188. } else if (checkCount >= maxChecks) {
  189. clearInterval(checkWpsSDK);
  190. console.error('[WPS] SDK 加载超时');
  191. error.value = 'WPS SDK 加载超时。请检查:\n1. 网络连接是否正常\n2. index.html 中的 SDK 脚本是否正确引入\n3. SDK CDN 地址是否可访问';
  192. loading.value = false;
  193. emit('error', error.value);
  194. }
  195. }, 100);
  196. });
  197. onBeforeUnmount(() => {
  198. destroyEditor();
  199. });
  200. // 暴露方法
  201. defineExpose({
  202. saveDocument,
  203. destroyEditor
  204. });
  205. </script>
  206. <style scoped lang="scss">
  207. .wps-editor-container {
  208. width: 100%;
  209. height: 100%;
  210. position: relative;
  211. .loading-container,
  212. .error-container {
  213. position: absolute;
  214. top: 50%;
  215. left: 50%;
  216. transform: translate(-50%, -50%);
  217. z-index: 10;
  218. display: flex;
  219. flex-direction: column;
  220. align-items: center;
  221. gap: 10px;
  222. .el-icon {
  223. font-size: 32px;
  224. color: #409eff;
  225. }
  226. }
  227. .wps-container {
  228. width: 100%;
  229. height: 100%;
  230. }
  231. }
  232. </style>