由于未找到wangeditor4版本的mention插件,所以自己来实现
第一步
监听change事件,在change事件中判断是否触发mention
editor.config.onchange = (html) => {
const selection = window.getSelection()
if (!selection.rangeCount) return
const range = selection.getRangeAt(0)
const textNode = range.startContainer
const cursorPos = range.startOffset
const textBeforeCursor = textNode.textContent.slice(0, cursorPos)
// 检测是否输入了符号
const atIndex = textBeforeCursor.lastIndexOf('@')
if (atIndex === -1) {
// 隐藏mention
this.showMention = false
return
}
const rect = range.getBoundingClientRect()
// 设置mention的位置
mentionPosition.left = rect.left + 'px'
mentionPosition.top = rect.bottom + 'px'
this.showMention = true
const queryStr = textBeforeCursor.slice(atIndex + 1)
// 过滤数据
}
第二步
用户选择mention后插入到文本中
handleSelect(item, notDelete) {
if (notDelete) {
//符号及搜索字符串删除
for (let i = -1; i < this.queryStr.length; i++) {
editor.cmd.do('delete')
}
}
const key = Date.now()
// 空格得带,否则属性会被清除
editor.cmd.do('insertHTML', `<span class="common-mention" id="${key}" data-id="${item.value}">${item.label}</span> `)
// 此处不能把空格删除,否则第二次插入变量时会出问题
this.$nextTick(() => {
// 需异步设置contenteditable,否则排版不对
document.getElementById(key).setAttribute('contenteditable', false)
})
}
以上仅为核心逻辑,选择框可自由发挥
二次选择
监听editor的点击事件,如果target是common-mention则显示选择框
handleEditorClick(event) {
const target = event.target;
if (target.classList.contains('common-mention')) {
this._targetMention = event.target
this.showMention = true
}
}
选择完后
mentionReplace(item) {
// 删除当前选中的提及元素
if (this._targetMention) {
const range = editor.selection.getRange()
range.selectNode(this._targetMention)
editor.selection.saveRange(range)
}
// 插入新选择的变量
this.handleSelect(item, true)
}
801

被折叠的 条评论
为什么被折叠?



