wangeditor4实现mention功能

由于未找到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>&nbsp;`)
      // 此处不能把空格删除,否则第二次插入变量时会出问题
      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)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值