本人用vue使用富文本編輯器踩了很多坑,特記下供大家借鑒。
剛開始使用的是kindeditor,在npm社區中找到了適用於vue的版本vue-kindeditor。存在如下缺陷:文檔不全、網上資料不全、npm社區實例過於簡單、上傳圖片不能控制圖片尺寸。
最終換用了wangEditor,優點:文檔齊全(有具體vue用法實例)、網上資料多、上傳圖片可以控制尺寸。
個人推薦wangEditor,官網wangEditor - 輕量級web富文本編輯器
前端vue
html: <div class="ArticleDetail"> <div ref="editor" style="text-align:left"></div> </div>
js: <script> import axios from axios; import {Loading} from element-ui import E from wangeditor var editor;
export default { name: "WriteArticle", data: function () { return { Title:, Content: } }, mounted:function(){ var That = this; editor = new E(this.$refs.editor); editor.customConfig = { onchange:function(html){ That.Content = html }, uploadImgServer: /api/UploadImg, // 上傳圖片到伺服器 uploadFileName : Content, //後端使用這個欄位獲取圖片信息 uploadImgMaxLength : 1 , // 限制一次最多上傳 1 張圖片 } editor.create() } } </script>
後端node.js
Express.post(/UploadImg,function (Request,Response) { var From = new Formidable.IncomingForm(); //設置保存 文件路徑 var TargetFile = Path.join(__dirname, ./Public/); From.uploadDir = TargetFile;
From.parse(Request, function (err, fields, files) { if (err) throw err; var FilePath = files.Content.path; //此content由前端uploadFileName設置 var NewPath = Path.join(Path.dirname(FilePath), files.Content.name); FS.rename(FilePath, NewPath, function (err) { if (err) throw err; var MyJson = { errno: 0, data:[http://localhost:8888/ + files.Content.name] }; Response.json(MyJson); }); }); });
三:代碼高亮
用了wangEditor才發現,3.0版的不支持代碼高亮。可是我的應用場景是我的博客,必須要有代碼高亮功能,無奈換掉編輯器。
經過一番對比又選了一個叫mavon-editor的基於vue實現的MakeDown編輯器。好處是使用真滴方便,而且可以與別的MarkDown編輯器實現直接複製文本。Github地址如下hinesboy/mavonEditor,按文檔操作即可
需要注意的地方是一般使用富文本的都是管理端,客戶端拿到MarkDown格式的數據需要使用maked組件轉成html格式的數據來展示。客戶端還需要引用一個樣式如下
<link href="https://cdn.bootcss.com/github-markdown-css/2.10.0/github-markdown.min.css" rel="stylesheet">
還需要在展示數據的容器上加上一個class,如:
<div class="markdown-body" v-html="Article.Content">{{ Article.Content }}</div>
推薦閱讀: