Vue2项目里WebSocket总断线?手把手教你封装一个带心跳和自动重连的稳定连接库
2026/5/3 15:43:25
作为山西软件工程专业的大三学生,我正在给自己的CMS新闻管理系统添加Word一键转存功能。核心需求包括:
import { ref, onMounted } from 'vue'; import 'xheditor/dist/xheditor.min.js'; import 'xheditor/dist/xheditor_lang/zh-cn.js'; export default { setup() { const editor = ref(null); onMounted(() => { // 初始化xhEditor $(editor.value).xheditor({ tools: 'full', // 全工具栏 upImgUrl: '/api/upload/image', // 图片上传接口 upImgExt: 'jpg,jpeg,gif,png', html5Upload: true, // 新增粘贴处理 pasteUpload: true, pasteUploadUrl: '/api/upload/paste', // 公式支持 latexUrl: '/api/latex/to-mathml' }); // 添加自定义按钮 addCustomButtons(); }); const addCustomButtons = () => { $.xheditor.tools.push({ name: 'importWord', title: '导入Word', icon: 'word-icon.png', handler: importWord }); }; const importWord = () => { const input = document.createElement('input'); input.type = 'file'; input.accept = '.doc,.docx'; input.onchange = async (e) => { const file = e.target.files[0]; if (!file) return; try { const formData = new FormData(); formData.append('file', file); const response = await fetch('/api/import/word', { method: 'POST', body: formData }); const result = await response.json(); if (result.success) { // 插入到编辑器 $(editor.value).xheditor('pasteHTML', result.html); } } catch (error) { console.error('Word导入失败:', error); } }; input.click(); }; return { editor, importWord }; } }true,'url'=>$ossUrl]);}catch(Exception$e){echojson_encode(['success'=>false,'message'=>$e->getMessage()]);}functionuploadToOSS($filePath,$fileName){require_once'oss-sdk/autoload.php';$accessKeyId=getenv('OSS_ACCESS_KEY_ID');$accessKeySecret=getenv('OSS_ACCESS_KEY_SECRET');$endpoint=getenv('OSS_ENDPOINT');$bucket=getenv('OSS_BUCKET');$ossClient=newOssClient($accessKeyId,$accessKeySecret,$endpoint);$object='uploads/'.date('Ymd').'/'.uniqid().'_'.$fileName;$ossClient->uploadFile($bucket,$object,$filePath);return'https://'.$bucket.'.'.$endpoint.'/'.$object;}getImageString());$ossUrl=uploadToOSS($imagePath,$image->getImageUri());unlink($imagePath);return$ossUrl;};// 转换HTML$htmlWriter=new\PhpOffice\PhpWord\Writer\HTML($phpWord);$htmlWriter->setImageHandler($imageHandler);$html=$htmlWriter->getContent();// 处理公式$html=convertLatexToMathML($html);echojson_encode(['success'=>true,'html'=>$html]);}catch(Exception$e){echojson_encode(['success'=>false,'message'=>$e->getMessage()]);}functionconvertLatexToMathML($html){// 正则匹配Latex公式$pattern='/\$\$(.*?)\$\$/';returnpreg_replace_callback($pattern,function($matches){$latex=$matches[1];// 调用KaTeX或MathJax转换$mathml=latexToMathML($latex);return$mathml;},$html);}我已经修改了xhEditor的源代码,添加了Word粘贴处理功能:
// xheditor-plugins/wordpaste.js$.xheditor.plugins.wordpaste={init:function(editor){editor.pasteUpload=true;editor.pasteUploadUrl='/api/upload/paste';editor.onPaste=function(e){if(editor.pasteUpload){e.preventDefault();constclipboardData=e.clipboardData||window.clipboardData;constitems=clipboardData.items;for(leti=0;i<items.length;i++){if(items[i].type.indexOf('text/html')!==-1){constblob=items[i].getAsFile();constreader=newFileReader();reader.onload=function(event){consthtml=event.target.result;uploadPastedContent(html);};reader.readAsText(blob);break;}}}};functionuploadPastedContent(html){// 发送到服务器处理fetch(editor.pasteUploadUrl,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({html:html})}).then(response=>response.json()).then(data=>{if(data.success){editor.pasteHTML(data.html);}});}}};使用MathJax实现Latex转MathML:
// latex-converter.jsfunctionlatexToMathML(latex){// 使用MathJax转换if(typeofMathJax!=='undefined'){returnMathJax.tex2mml(latex);}// 备用方案:使用KaTeXif(typeofkatex!=='undefined'){returnkatex.renderToString(latex,{output:'mathml',throwOnError:false});}// 最简方案:使用图片return``;}推荐购买"mammoth.js"的商业授权(个人版仅需$9.99),用于Word转HTML:
// 使用mammoth.js转换Word文档importmammothfrom'mammoth';mammoth.extractRawText({arrayBuffer:fileArrayBuffer}).then(result=>{consthtml=result.value;// 获取HTML内容constmessages=result.messages;// 获取转换消息// 处理图片returnprocessImages(html);}).then(html=>{// 插入编辑器editor.pasteHTML(html);});// oss-upload.phprequire_once'oss-sdk/autoload.php';$accessKeyId="您的AccessKeyId";$accessKeySecret="您的AccessKeySecret";$endpoint="oss-cn-hangzhou.aliyuncs.com";$bucket="您的Bucket名称";functionuploadToOSS($filePath,$object){global$accessKeyId,$accessKeySecret,$endpoint,$bucket;try{$ossClient=newOssClient($accessKeyId,$accessKeySecret,$endpoint);$options=array(OssClient::OSS_CHECK_MD5=>true,OssClient::OSS_PART_SIZE=>5*1024*1024);$ossClient->uploadFile($bucket,$object,$filePath,$options);return$ossClient->getObjectUrl($bucket,$object);}catch(OssException$e){returnfalse;}}作为即将毕业的学长,我有几点建议:
欢迎加入我们的技术交流群(QQ:223813913),你将获得:
记住我们的口号:“代码改变命运,群友共同富裕!” 🚀
在工具栏中添加插件按钮
一键粘贴Word内容,自动上传Word中的图片,保留文字样式。
一键导入Word文件,并将Word文件转换成图片上传到服务器中。
一键导入PDF文件,并将PDF转换成图片上传到服务器中。
一键导入PPT文件,并将PPT转换成图片上传到服务器中。
一键自动上传网络图片,自动下载远程服务器图片,自动上传远程服务器图片
点击下载完整示例