Skip to content

mention渲染出来info没有数据的解决方法/自定义样式 #17

Open
@codecnmc

Description

昨天突然需要一个@提及的方法 发现v5版本有插件 所以昨天从v4版本升级v5 两者的差异的初始化有点大
遇到一个问题 所有渲染的mention的Node 插入到编辑器里 都是data-slate-node="element"的存在 只能把value渲染出来 导致要显示的值是name 但是实际操作的值提醒的人是user_id 不可能把user_id显示到屏幕上吧 看了半天的源代码 包太分散太复杂了 感觉是模块下的elem-to-html没有应用到

解决方法1:直接提交富文本的时候将编辑器所有children拿出来 递归筛选出type为mention的节点

// 每次提交的时候调用方法获取id
getMentionList() {
      let mentionSet = new Set()
      const getMention = item => {
        if (item.type == 'mention') {
          mentionSet.add(item.info.id)
        }
        item.children &&
          item.children.forEach(child => {
            getMention(child)
          })
      }
      this.editor.children.forEach(x => {
        getMention(x)
      })
      return [...mentionSet]
}

问题来了 我觉得样式不够美观 而且 我想修改基础样式 并且当被@到的人 进来页面高亮显示
解决方法2:直接修改renderMention模块 在注册前修改 不需要修改源码文件 更换环境也不受影响

import mentionModule from '@wangeditor/plugin-mention'
import MentionModal from './MentionModal'
mentionModule.renderElems[0].renderElem = function (elem, children, editor) {
  // 当前节点是否选中
  const selected = DomEditor.isNodeSelected(editor, elem)
  const { value = '', info } = elem
  // 构建 vnode
  const vnode = h(
    'span',
    {
      props: {
        contentEditable: false, // 不可编辑
      },
      // 自定义的属性 这个h的class没有效果 所以直接再attrs下编写
      attrs: {
        'data-id': info.id,
        class: 'w-mention',
      },
      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
}

image

在标签中有自定义的class 也可以直接修改style里样式
所以可以

::v-deep .w-mention {
  cursor: pointer !important;
  color: red;
}

导出的富文本html里面也有需要的数据
image

我是两种方法结合使用 第二种是写前端被提醒者查看时高亮提醒 第一种是我写后端的时候set拿到的id不会重复 我就可以安心做我的提醒操作

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions