MonacoEditor在vue中的使用

当时寻找的时候发现,大量的参考资料都是关于react中如何使用MonacoEditor,踩了很多坑,于是打算在这里记下来.

首先说一下,为什么要选取MonacoEditor而不是codemirror

1,支持代码的折叠展开

2.可以实现自动格式化json




接下来直接进入正题,首先使用npm install vue-monaco-editor

我使用的日期是2020年3月18日,此时的vue-monaco-editor是存在一定的问题的,他的一些设置项是不生效的,追更溯源,封装的时候有点出入.所以我直接将下载好的vue-monaco-editor依赖从node_modules中拿出来,直接放入项目中引入.



具体使用如下

1.引入

 import MonacoEditor from './vue-monaco-editor/src/Monaco'

2,使用

<MonacoEditor

        height="600"

        language="json"

        :code="code"

        :editorOptions="options"

        @mounted="onMounted"

        @codeChange="onCodeChange"

        >

    </MonacoEditor>

其中,options是空对象(与上文相应.封装存在问题,所以不再外面进行配置,直接进入Monaco.vue中改动),

code是我们需要展示的内容,

language是支持的语言,目前我只尝试了json,别的具体请参考官网.

onMounted和onCodeChange,一个是挂载,一个是改变编辑器内容的出发方法,建议如下书写


onMounted (editor) {

        this.editor = editor;       

      },

onCodeChange(editor) {},

(其中editor需要再data中声明,初始化为null即可)

3,格式化json内容

this.editor.updateOptions({

            readOnly: false //是否只读

});

this.editor.setValue(this.params) // 参数是编辑器需要展示的json串

this.editor.trigger('','editor.action.format') // 触发自动格式化

this.editor.setValue(this.editor.getValue()) // 强制刷新一次

this.editor.updateOptions({

            readOnly: true

});


4,配置项


在data中,其中以下配置项可以参考官方文档,此处配置即可生效

defaults: {

        selectOnLineNumbers: true,

        roundedSelection: false,

        readOnly: false,

        cursorStyle: 'line',

        automaticLayout: true,

        glyphMargin: true,

        showFoldingControls: "always",

        formatOnPaste: true,

        formatOnType: true,

        folding: true

      }

    }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容