话不多说 直接上代码!!!
html中得先引用wangEditor插件
vue中使用:
1.npm install wangeditor (注意 wangeditor 所有是小写字母)html
2.引入import E from “wangeditor”; //引入富文本插件
或者
直接引用wangEditor的js
//html中
<div id="editor" v-model="Form.showContent">
<!-- <p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p> -->
</div>
js中先创建富文本
init() {
const E = window.wangEditor;
this.editor = new E(document.getElementById('editor'));
this.editor.customConfig.uploadImgMaxSize = 10 * 1024 * 1024; // 将图片大小限制为 10M
this.editor.customConfig.uploadImgMaxLength = 1; // 限制一次最多上传 1 张图片
this.editor.customConfig.showLinkImg = false; //隐藏网络图片上传
this.editor.customConfig.uploadImgHooks = {
fail: function(xhr, editor, result) {
//上传错误时触发
alert("上传图片失败");
}
};
// 自定义上传图片事件
this.editor.customConfig.customUploadImg = function(files, insert) {
// file是是input中选中的文件列表
// insert是获取图片url后,插入到编辑器中的方法
var formData = new FormData();
var obj = {};
for (var i = 0; i < files.length; i++) {
obj = files[i]
}
//后端所需的参数
formData.append('file', obj);
console.log(obj);
formData.append('merchantId', '');
$.ajax({
url: url + '调用服务器的接口',
type: "POST",
data: formData,
async: false,
dataType: "json",
xhrFields: {
withCredentials: true
},
crossDomain: true,
cache: false,
contentType: false,
processData: false,
success: function(da) {
console.log(da);
// insert(da.avatarUrl);
if (da.code == 1 || da.code == "1") {
// 上传代码返回结果之后,将图片插入到编辑器中
insert(da.data.avatarUrl);
} else {
alert(da.message);
return;
}
}
});
};
this.editor.customConfig.customAlert = function(info) {
// info 是需要提示的内容
alert('自定义提示:' + info)
}
this.editor.customConfig.withCredentials = true;
this.editor.create();
}
要想让富文本只查看不编辑
①只需在富文本编辑器中使用v-html,此处展示的是页面形式
//detail接收返回来的值
<editor-bar id="editor" v-model="detail" v-html="detail"></editor-bar>
②让wangEditor设置不可编辑,在创建富文本编辑器之后
this.editor.customConfig.onchange = (html) => {
this.detail = html;
};
this.editor.$textElem.attr('contenteditable', false)
//获取后端返回的富文本值
this.editor.txt.text(detail)
最终提交给后端
//判断是否为空
//如果每次输入数据都多<p></p>,则用this.editor.txt.html().replace(/<p><\/p>/g, '');
let content1 = this.editor.txt.html();
if (content1 === '<p><br></p>') {
this.detailContext = '';
} else {
this.detailContext = content1;
}