當時尋找的時候發(fā)現(xiàn),大量的參考資料都是關(guān)于react中如何使用MonacoEditor,踩了很多坑,于是打算在這里記下來.
首先說一下,為什么要選取MonacoEditor而不是codemirror
1,支持代碼的折疊展開
2.可以實現(xiàn)自動格式化json
接下來直接進入正題,首先使用npm install?vue-monaco-editor
我使用的日期是2020年3月18日,此時的vue-monaco-editor是存在一定的問題的,他的一些設(shè)置項是不生效的,追更溯源,封裝的時候有點出入.所以我直接將下載好的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是空對象(與上文相應(yīng).封裝存在問題,所以不再外面進行配置,直接進入Monaco.vue中改動),
code是我們需要展示的內(nèi)容,
language是支持的語言,目前我只嘗試了json,別的具體請參考官網(wǎng).
onMounted和onCodeChange,一個是掛載,一個是改變編輯器內(nèi)容的出發(fā)方法,建議如下書寫
onMounted?(editor)?{
????????this.editor?=?editor;???????
??????},
onCodeChange(editor)?{},
(其中editor需要再data中聲明,初始化為null即可)
3,格式化json內(nèi)容
this.editor.updateOptions({
????????????readOnly:?false //是否只讀
});
this.editor.setValue(this.params) // 參數(shù)是編輯器需要展示的json串
this.editor.trigger('','editor.action.format') // 觸發(fā)自動格式化
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
??????}
????}