wangEditor 定义新元素,insertNode,出现异常 (Cannot resolve a DOM node from Slate node: {"text":""})

hsvhsicv  于 4个月前  发布在  其他
关注(0)|答案(1)|浏览(45)

效果

@功能

版本

wangEditor v5 ,vue2

封装

import { h } from 'snabbdom'
import { DomEditor  } from '@wangeditor/editor'
// 定义inline和void插件

function withMetion(editor) {
  const { isInline } = editor
  const newEditor = editor
  newEditor.isInline = elem => {
    const type = DomEditor.getNodeType(elem)
    if (type === 'mention') return true
    return isInline(elem)
  }
  return newEditor
}
// 渲染“@人”元素到编辑器
function renderMention(elem, editor) {
  // 当前节点是否选中
  const selected = DomEditor.isNodeSelected(editor, elem)
  const { value = '' } = elem
  // 构建 vnode
  const vnode = h(
    'span',
    {
      props: {
        // 不可编辑
        contentEditable: false,
      },
      style: {
        marginLeft: '3px',
        marginRight: '3px',
        backgroundColor: 'var(--w-e-textarea-slight-bg-color)',
        // 选中/不选中,样式不一样
        border: selected
          ? '2px solid var(--w-e-textarea-selected-border-color)' // wangEditor 提供了 css var https://www.wangeditor.com/v5/theme.html
          : '2px solid transparent',
        borderRadius: '3px',
        padding: '0 3px',
      },
    },
    `@${value}`
  )
  return vnode
}
// 解析 HTML 字符串,生成“@人”元素
function mentionParseHtml(elem) {
  // elem HTML 结构 <span data-w-e-type="mention" data-w-e-is-void data-w-e-is-inline data-value="张三" data-info="xxx">@张三</span>
  const value = elem.getAttribute('data-value') || ''
  return {
    type: 'mention',
    value,
    children: [{ text: '' }], // void node 必须有一个空白 text
  }
}
// 生成“@人”元素的 HTML
function mentionToHtml(elem) {
  const { value = '' } = elem
  return `<span data-w-e-type="mention" data-w-e-is-void data-w-e-is-inline data-value="${value}">@${value}</span>`
}
const mentionToHtmlConf = {
  type: 'mention',
  elemToHtml: mentionToHtml,
}
const renderMentionConf = {
  type: 'mention',
  renderElem: renderMention,
}
const metionParseHtmlConf = {
  selector: 'span[data-w-e-type="mention"]',
  parseElemHtml: mentionParseHtml,
}

const metionModule = {
  editorPlugin: withMetion,
  renderElems: [renderMentionConf],
  elemsToHtml: [mentionToHtmlConf],
  parseElemsHtml: [metionParseHtmlConf]
}

export default metionModule

注册

import { Boot } from '@wangeditor/editor'
import mention from '@/components/mainChat/components/enter/customDom/mention.js'
// @人元素
Boot.registerModule(mention)

使用

node.type = 'mention'
      node.value = data.content
      node.children = [{ text: '' }]
      this.editor.insertNode(node)

相关问题