---
title: "setContent 命令"
description: "使用 setContent 命令用新的 JSON 或 HTML 替换文档。了解更多内容请查阅我们的文档！"
canonical_url: "https://tiptap.zhcndoc.com/editor/api/commands/content/set-content"
---

# setContent 命令

使用 setContent 命令用新的 JSON 或 HTML 替换文档。了解更多内容请查阅我们的文档！

`setContent` 命令用新内容替换文档。您可以传递 JSON 或 HTML。这基本上与在初始化时设置 `content` 相同。

另请参见: [insertContent](https://tiptap.zhcndoc.com/editor/api/commands/content/insert-content.md), [clearContent](https://tiptap.zhcndoc.com/editor/api/commands/content/clear-content.md)

## 参数

### content

新的内容，作为字符串（JSON 或 HTML），Fragment 或 ProseMirror 节点。编辑器将仅根据 [schema](https://tiptap.zhcndoc.com/editor/core-concepts/schema.md) 渲染允许的内容。

### options

可选配置对象，包含以下属性：

`parseOptions?: Record<string, any>`
配置解析的选项。有关 parseOptions 的更多信息，请参考 [ProseMirror 文档](https://prosemirror.net/docs/ref/#model.ParseOptions)。

`errorOnInvalidContent?: boolean`
如果内容无效，是否抛出错误。

`emitUpdate?: boolean (true)`
是否发出更新事件。默认为 `true`（注意：在 v2 中此项由 `false` 改为 `true`）。

## 示例

```js
// 普通文本
editor.commands.setContent('示例文本')

// HTML
editor.commands.setContent('<p>示例文本</p>')

// JSON
editor.commands.setContent({
  type: 'doc',
  content: [
    {
      type: 'paragraph',
      content: [
        {
          type: 'text',
          text: '示例文本',
        },
      ],
    },
  ],
})

// 带选项
editor.commands.setContent('<p>示例文本</p>', {
  emitUpdate: false,
  parseOptions: {
    preserveWhitespace: 'full',
  },
  errorOnInvalidContent: true,
})
```
