前言
最近在使用
uniapp
自带的editor
组件开发的时候,遇到了一些问题,现将问题和解决方法做一个总结
editor
组件使用方法可参阅 👉 猛戳这里
有以下几个问题:
- 使用
input
事件做富文本内容赋值,每次输入,光标会跳到最前面。 - 使用
editor
组件回填时,点击其他地方会失焦
,将原本回填内容清空。
接下来看一段代码👇
<editor id="editor" class="ql-container" placeholder="编辑..."
@ready="onEditorReady"
@statuschange="onStatusChange"
@input="handleEditorInput"
@blur="handleEditorBlur">
</editor>
// 编辑器初始化完成时触发
onEditorReady() {
uni.createSelectorQuery().select("#editor").context(function (t) {
e.editorCtx = t.context;
}).exec();
},
// 通过setContents设置内容
this.editorCtx.setContents({
html: this.content
});
// 如果这样赋值,光标会在每次输入跳到最前面
// 小伙伴们可以在自己电脑上试下,
handleEditorInput(e) {
this.content = e.detail.html;
},
解决办法就是 当它
失焦
再进行赋值
就有下面的代码:
handleEditorBlur(e) {
console.log("handleEditorBlur>>", e.detail.html);
this.content = e.detail.html;
},
光标的问题可以解决了,但是回填 清空的问题就出现,如下图:
⭐️获取到数据回填到编辑器,失焦之后内容清空,此时内容是 <p><br></p>
,这个问题解决起来不难。
解决方法如下:
handleEditorBlur(e) {
console.log("handleEditorBlur>>", e.detail.html);
if (e.detail.html === '<p><br></p>') {
return
}
this.content = e.detail.html;
},
思考
🌈第2个问题解决起来并不难,但是为什么会清空,这才是值得去思考的问题。笔者猜测是editor 组件回填,这个内容并没有赋值给事件对象,所以拿到的是 <p><br></p>
,再进行失焦,就清空了。大佬路过,有更好的办法,可以留下你的足迹。