ProseMirror在Vue组件中初始化时内容不显示怎么办?

长孙运来 阅读 63

我在Vue组件里用ProseMirror写富文本编辑器,初始化的时候传了content属性但内容始终不显示出来,这是为什么呢?

代码是这样写的:



  
import { EditorState, EditorView } from 'prosemirror-state'; import { schema } from 'prosemirror-schema-basic'; export default { props: ['content'], data() { return { editor: null }; }, mounted() { const state = EditorState.create({ schema, doc: this.content }); this.editor = new EditorView(this.$refs.editor, { state }); } }

我尝试过在mounted里直接打印this.content能看到正确的初始值,但编辑器里就是空白。换成静态字符串写死就能显示,动态传值就不行了…

我来解答 赞 6 收藏
二维码
手机扫码查看
1 条解答
程序猿书妍
嗯,这个问题我遇到过。主要是因为 this.content 虽然在 mounted 里能打印出来,但它的数据类型可能不符合 ProseMirror 的要求。ProseMirror 的 doc 需要的是一个具体的 Schema 节点结构,而不是纯文本或 HTML 字符串。

解决办法就是在初始化之前,先把 this.content 转换成符合 Schema 的节点。可以这样改:

import { EditorState, EditorView } from 'prosemirror-state';
import { schema } from 'prosemirror-schema-basic';
import { DOMParser } from 'prosemirror-model';

export default {
props: ['content'],
data() {
return {
editor: null
};
},
mounted() {
const parser = new DOMParser(schema);
const doc = parser.parse(this.content); // 这里把字符串转成节点
const state = EditorState.create({ schema, doc });
this.editor = new EditorView(this.$refs.editor, { state });
}
}


重点就是用 DOMParser 把内容解析成正确的节点结构。WP里面如果对接富文本编辑器,这种转换也是常见的操作。记得检查 this.content 的格式是不是合法的 HTML,不然也可能会有问题。

另外提醒一下,如果内容是异步加载的,可能还需要加个判断,确保数据准备好后再初始化编辑器。
点赞 14
2026-02-01 14:03