首页 文章

重置Monaco Editor状态

提问于
浏览
0

我已经实现了Monaco编辑器(https://github.com/Microsoft/monaco-editor)作为用户插入一些JSON的方式 .

一旦用户点击“发布”按钮,我就启用编辑器 . 问题是,编辑器在开关功能内启用 . 因此,一旦单击按钮一次,编辑器将添加到第一个创建的编辑器下方,如果客户端再次单击相同的按钮 . 有没有办法“重置”编辑器,所以它实际上不会附加,而是要么换一个新的,还是使用已经创建的那个?

这是我目前的代码 .

require.config({ paths: { 'vs': '/scripts/monaco-editor/min/vs' } });

switch (id) {
        case 'post':
            $('#httpMethodGet').css('display', 'none');
            $('#httpMethodPost').show();
            require(['vs/editor/editor.main'], function () {
                monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
                    schemas: [{
                        uri: "http://myserver/bar-schema.json",
                        schema: {
                            type: "object",
                            properties: {
                                q1: {
                                    enum: ["x1", "x2"]
                                }
                            }
                        }
                    }]
                });
                var jsonObject = [
                    '{',
                    '    "$schema": "http://myserver/foo-schema.json"',
                    "}"
                ].join('\n');
                window.editor = monaco.editor.create(document.getElementById('codeEditor'), {
                    value: jsonObject,
                    language: 'json',
                    theme: 'vs-dark',
                    scrollBeyondLastLine: false,
                    renderWhitespace: true
                });
            });
            break;

因此,我希望 window.editor = monaco.editor.create(document.getElementById('codeEditor'), {}) 使用已创建的相同内容,如果有一个已创建,或者每次创建一个新的情况,则每次输入此开关案例时,它都不会附加到已创建的那个 .

1 回答

  • 1

    您应该在开关功能旁边创建monaco代码编辑器 . 在您的功能内部,您应该只更改您的模型 .

    所以在 switch() 函数之前

    window.editor = monaco.editor.create(document.getElementById('codeEditor'), {
                        value: '',
                        language: 'json',
                        theme: 'vs-dark',
                        scrollBeyondLastLine: false,
                        renderWhitespace: true
                    });
    

    然后在 switch()

    window.editor.getModel(). setValue(jsonObject);
    

    API可用here .

相关问题