美文网首页
MonacoEditor在vue中的使用

MonacoEditor在vue中的使用

作者: 小话梅噢 | 来源:发表于2020-03-18 17:04 被阅读0次

当时寻找的时候发现,大量的参考资料都是关于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

      }

    }

相关文章

网友评论

      本文标题:MonacoEditor在vue中的使用

      本文链接:https://www.haomeiwen.com/subject/bhdcyhtx.html