wangEditor使用踩坑记录
wangEditor是一款轻量级富文本编辑器,虽然功能非常强大,但是在使用中还是踩了不少坑,下面具体说说我在项目使用中遇到的坑,此次我在移动端使用wangEditor。
1.editor.focus()后光标显示在文本最前面
在移动端插入图片时,需要先调用系统相册选择相片再做插入,点击调用系统相册时编辑器就会失去焦点,这个在插入图片之前就需要调用editor.focus() 进行聚焦再插入。但是此时光标聚焦在最前面,插入的位置就不对。这个时候我就阅读文档使用,
editor.focus(true)// 选区定位到最后
此时光标会聚焦在文本的最末尾,但是我们是想聚焦在上次失焦的位置,所以这个方法也不行。最后终于找到方法,
this.editor.restoreSelection() // 恢复选区,会自动聚焦到上次失焦位置
let html = '<img src="' + url + '"/>'
this.editor.dangerouslyInsertHtml(html) // 插入 html
2.表情连续输入时键盘不能弹起,且按顺序输
在输入表情时如果需要连续输入, 则不能用this.editor.restoreSelection() ,因为这会自动唤起键盘,此时要让输入在上次光标失焦的地方,就要想别的办法了。这个时候就要使用到slate.js的Transforms了。
import { Transforms } from 'slate' // 引入
// 展开表情输入区时记录编辑器选区
openEmoji() {
this.isShowEmoji = true
this.previousSelection = Object.assign({}, this.editor.selection)
},
// 插入节点
insertNode(item, type) {
let node = {}
node = {
type: 'emoji',
src: item.src, // 必须是 'emoji'
tag: item.tag,
children: [{ text: '' }], // 必须有一个空 text 作为 children
}
// 保持输入表情时可以在上次光标失焦的位置插入表情
Transforms.select(this.editor, this.previousSelection)
// 连续输入表情时第一个表情输入
if (this.previousSelection.focus.offset != 0) {
this.editor.insertNode(node)
} else {
// 连续输入表情时第二、三.....个表情输入
Transforms.insertNodes(
this.editor,
node,
{
at: this.previousSelection,
select: true
}
)
}
let focusOffset = 0
let focusPath = [this.previousSelection.focus.path[0], this.previousSelection.focus.path[1]+2]
let anchorOffset = 0
let anchorPath = [this.previousSelection.anchor.path[0],this.previousSelection.anchor.path[1]+2]
let newSelection = {
anchor: { path: focusPath, offset: focusOffset },
focus: { path: anchorPath, offset: anchorOffset },
}
this.previousSelection = newSelection
}
连续输入表情时,第一次输入用editor.insertNode(node)
,后面用Transforms.insertNodes
,是因为,如果都用editor.insertNode(node)
新插入的表情会插入在上次失焦的位置,导致连续表情输入的排列是倒序的,目前的写法虽然可以解决现有的问题,但我认为这不是很好的写法,如果能对wangEditor和slate.js了解的更深的话,一定还有更好的写法,也欢迎大家补充。
3.实现图片输入后光标换行显示
在移动端编辑器上,图片输入之后按宽度100%展示,此时希望输入聚焦之后,光标能换行显示,那么我们就在输入聚焦之后将光标后移以为并执行换行就可以了。
this.editor.restoreSelection() // 恢复选区
let html = '<img src="' + url + '"/>'
this.editor.dangerouslyInsertHtml(html) // 插入 image
this.editor.move(1) // 后移光标
this.editor.insertBreak() // 换行
4.组件销毁时,及时销毁编辑器
beforeDestroy() {
const editor = this.editor
if (editor == null) return
editor.destroy() // 组件销毁时,及时销毁编辑器
}
以上这些是我在使用这款编辑器时碰到的一些难点,还有更多难点也欢迎大家评论交流~,下篇笔者会介绍一下wangEditor如何自定义模板插件。