参考:wangEditor官网
项目:vue实现:使用富文本编辑器插件,支持部分文字加粗、下划线和字体调整
<template>
<div>
<div class="editor_container" :class="{'is-error': isError}">
<div :id="uniqEditorId" class="inner"></div>
</div>
<div>{{htmlContent}}</div>
</div>
</template>
<script lang="ts">
import { Component, Mixins, Watch } from 'vue-property-decorator';
import Editor from 'wangeditor';
@Component({
name: 'TextEditor'
})
export default class TextEditor extends Mixins(xxx) {
textContent? :string = ''; // 文本框内容 text
htmlContent?:string = '' // html内容
uniqEditorId: string = 'div-' + Math.random().toString(36).substr(3); // 随机id
editor? = null;
isError: boolean = false; // 是否无值
/**
* 必填校验
*/
check(this: any) {
if (要求必填) {
// 通过html和text判断(htmlContente是html类型,textContent是text类型)
this.isError = !htmlContent || !this.textContent;
return !!this.htmlContent && !!this.textContent;
} else {
this.isError = false;
return true;
}
}
mounted(this: any) {
this.editor = new Editor(document.getElementById(this.uniqEditorId));
this.editor.config.showFullScreen = false; // 取消全屏
this.editor.config.pasteIgnoreImg = true; // 忽略粘贴内容中的图片
this.editor.config.height = 200; // 设置编辑区域高度为 200px
this.editor.config.onchangeTimeout = 300; // 配置触发 onchange 的时间频率,默认为 200ms
// 配置菜单栏,删减菜单,调整顺序
this.editor.config.menus = [
'bold',
'underline',
'fontName'
]
// 配置粘贴文本的内容处理
this.editor.config.pasteTextHandle = (pasteStr: any) => {
// 对粘贴过来的内容(html 或 纯文本),可进行自定义处理然后返回,主要可以处理word文本
console.log(pasteStr,'pasteStr~~~~~~~~~~~')
// content
if (pasteStr === '' && !pasteStr) return ''
var str = pasteStr
str = str.replace(/<xml>[\s\S]*?<\/xml>/ig, '')
str = str.replace(/<style>[\s\S]*?<\/style>/ig, '')
str = str.replace(/<\/?[^>]*>/g, '')
str = str.replace(/[ | ]*\n/g, '\n')
str = str.replace(/ /ig, '')
return str
}
// 配置 onchange 回调函数
this.editor.config.onchange = (newHtml:any) => {
this.htmlContent = newHtml;
this.textContent = this.editor.txt.text(); // 存来校验用
};
this.editor.create();
this.editor.txt.html(this.htmlContent); // 重新设置编辑器内容(用于将保存的值在进入页面时回西显到编辑器中)
//获取文本 将text存入data,作必填校验适用
this.textContent = this.editor.txt.text();
}
beforeDestroy(this:any) {
// 销毁编辑器
if(this.editor) {
this.editor.destroy();
}
this.editor = null;
}
}
</script>
<style lang="less">
.editor_container {
.inner {
.w-e-toolbar {
z-index: auto!important;
}
.w-e-text-container {
z-index: auto!important;
}
u {
display: inline; // 因为被全局覆盖,所以重新写一下
}
}
&.is-error{ // 红框:代表必填
border: 1px solid #f56c6c;
.inner {
.w-e-toolbar {
border: none!important;
border-bottom: 1px solid #eeeeee!important;
}
.w-e-text-container{
border: none!important;
}
}
}
}
</style>
推荐一篇收藏好文:https://blog.csdn.net/qq_28353055/article/details/103480821?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_title~default-0.no_search_link&spm=1001.2101.3001.4242.1