背景
近期做的后台管理系统,需要有一个富文本编辑器来录入一些API文档的功能。调研时,用UEditor,去github直接下资源包,然后引入到项目中。然而由于项目是一个vue项目,UEditor的实现有些似乎类型JQuery的使用,引入项目中一直各种报错。想着技术都比较旧,后期用富文本的功能报错也不好处理,最后弃了。然后用了vue2-editor,实现简单,初始首版就用vue2-editor去实现了。后来,需求要求要插入表格功能,vue2-editor不支持插入表格功能。自定义扩展,也不好扩展。去npm也查了下,时经2年也没有更新了,也没有专门团队去维护。后来查富文本就查到了wangeditor插件,功能比较多,还有专门文档手册,有专门团队维护,即使添加自定义菜单,文档中也可以查的到。而且,插件还是用TypeScript是实现开发的。近期还有新版本增加。就美美地,尝试着在项目里面引入试用了。
问题
兴冲冲地按着文档使用方法去新增富文本功能,以为可以完美实现,结果第一步创建富文本就出现了警告信息,导致添加富文本失效。
警告信息如下:
addRange(): The given range isn’t in document
解决
看到警告,第一做法就是直接复制信息问了下度娘。然而查了十来分钟,找的法子跟自己的都不是很适合,没有解决。最后干脆自己尝试着去看报错信息试着去解决。
看着警告意思,大概的意思是说给定的对象不在文档范围,结合wangeditor的使用文档,创建富文本时,是要指定容器的。我做的是vue项目,由于存在虚拟DOM机制,导致在创建富文本对象时可能拿不到这个容器,这就和提到不在文档范围吻合了。朝着这方向去试着处理,竟然解决了。上代码如下。
editor.vue
<template>
<div>
<div id="edtior"></div>
</div>
</template>
editor.ts
<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'
import WangEditor from 'wangeditor'
@Component({
name: 'modify-dialog'
})
export default class ModifyDialog extends Vue{
prefixCls : string = 'modify-document-dialog'
wangEditor : any = null
/**
* 编辑器配置
*/
setEditorConfig() {
// 设置菜单
this.wangEditor.config.menus = [
'head',
'bold',
'fontSize',
'fontName',
'italic',
'underline',
'strikeThrough',
'indent',
'lineHeight',
'foreColor',
'backColor',
'link',
'list',
'todo',
'justify',
'quote',
'emoticon',
'image',
'table',
'code',
'splitLine',
'undo',
'redo',
]
// 设置编辑区域的高度
this.wangEditor.config.height = 500
/* ========= 图片上传 start =========== */
// 配置 server 接口地址
this.wangEditor.config.uploadImgServer = '/upload-img'
// 可使用 base64 格式保存图片
this.wangEditor.config.uploadImgShowBase64 = true
/* ========= 图片上传 end =========== */
// 网络图片-配置alt选项
this.wangEditor.config.showLinkImgAlt = false
// 网络图片-配置超链接
this.wangEditor.config.showLinkImgHref = false
// 配置 onchange 回调函数,将数据同步到 vue 中
this.wangEditor.config.onchange = (newHtml: any) => {
(this as any).form.documentContent = newHtml
}
}
initWangEditor() {
this.wangEditor = new WangEditor('#edtior')
// 编辑器配置
this.setEditorConfig()
// 创建编辑器--把wangEditor.create()放在$nextTick里面,加一个异步延迟的处理,就可以正常创建富文本编辑器了
this.$nextTick(() => {
this.wangEditor.create()
// 设置编辑器内容
this.wangEditor.txt.html((this as any).form.documentContent)
})
}
created() {
this.initWangEditor()
}
}
</script>
以上,问题解决。
如有问题,欢迎来指出呀!