在vue中使用monaco-editor
1.初始化
<div ref="codeContainer" style="height: 380px" />
import * as monaco from monaco-editor/esm/vs/editor/editor.api
this.editMsg = monaco.editor.create(this.$refs.codeContainer, {
value: , // 默认值
readOnly: true, // 是否只读
lineNumbers: true, // 是否显示行数
theme: vs-dark, // 编辑器主题
lineHeight: 20, // 行高
tabSize: 2, // 缩进
automaticLayout: true, // 是否自适应宽高,设置为true的话会有性能问题
language: python // 语言,需要引入相应文件
})
注意: div要添加高度,如果不添加高度,monaco高度就为0,无法显示出来
2.修改属性updateOptions
updateOptions可用于修改monaco的readonly等属性 设置value使用this.editMsg.setValue(value) 设置language需要先销毁编辑器,再重新定义
3.语言包的引入
vue中下载所有包都在node_modules文件夹下,monaco的所有语音包都存放在node_modules/monaco-editor/esm/vs/basic-langules文件夹内 举个例子:如果要引入JavaScript语言包,就应该这样写:
import monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution
4.事件
编辑器内容修改事件
this.editor.getModel().onDidChangeContent((e) => {
// ...
})
5.插入修改文本
插入文本:
const selection = this.editor.getSelection()
this.editor.executeEdits(insert-code, [
{
range: new monaco.Range(
selection.endLineNumber,
selection.endColumn,
selection.endLineNumber,
selection.endColumn
),
text: content
}
])
6.销毁
this.editMsg.dispose()
