tiptap content 文档命令

tiptap content 文档命令包含clearContent 清除文档、insertContent 插入内容、insertContentAt 插入制定位置内容、setContent 设置新的内容等核心命令。

clearContent 清除内容

清除编辑器里面的内容,但在运行该命令之后,编辑器文档也将至少有一个(空)段落

// 移除编辑器文档内容
editor.commands.clearContent()

//移除编辑器文档内容,并触发 update 事件
editor.commands.clearContent(true)

insertContent 插入内容

插入node节点或html字符串到当前光标位置

// 插入纯文本
editor.commands.insertContent('Example Text')

// 插入HTML字符串
editor.commands.insertContent('<h1>Example Text</h1>')

// 插入字符串去除两边空格
editor.commands.insertContent(' <h1>Example Text </h1> ', 
{
  parseOptions: {
    preserveWhitespace: false,
  }
})

// 插入 Json节点
editor.commands.insertContent({
  type: 'heading',
  attrs: {
    level: 1,
  },
  content: [
    {
      type: 'text',
      text: 'Example Text',
    },
  ],
})

// 插入多个节点
editor.commands.insertContent([
  {
    type: 'paragraph',
    content: [
      {
        type: 'text',
        text: 'First paragraph',
      },
    ],
  },
  {
    type: 'paragraph',
    content: [
      {
        type: 'text',
        text: 'Second paragraph',
      },
    ],
  },
])

insertContentAt 插入制定位置

insertContentAt 插入内容到制定位置或区间,参数如下:

  • position number | Range 位置或区间

  • value 插入的内容字符串或JSON节点

  • options {updateSelection,parseOptions} 详情

editor.commands.insertContentAt(12, '<p>www.itxst.com</p>', {
  updateSelection: true,
  parseOptions: {
    preserveWhitespace: 'full',
  }
})

setContent 覆盖内容

setContent 回完全覆盖编辑器的内容,不保留原来的内容,可以是htmljson字符串,参数如下:

参数说明
content:stringJSON 或 HTML
emitUpdate?: Boolean (false)是否触发 update 事件,默认为 false
parseOptions?: Record<string, any>点击查看
// HTML
editor.commands.setContent('<p>Example Text</p>')

// JSON
editor.commands.setContent({
  "type": "doc",
  "content": [
    {
      "type": "paragraph",
      "content": [
        {
          "type": "text",
          "text": "Example Text"
        }
      ]
    }
  ]
})

下载教程 Demo

本教程Demo的源码点击这里下载,Tiptap Demo,下载完成后运行npm i初始化依赖包。