1.安装
npm install monaco-editor@0.21.2 --save
npm install monaco-editor-webpack-plugin --save
2.项目配置
在vue.config.js追加
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')
module.exports = {
//忽略部分其他配置代码
chainWebpack: (config) => {
config.plugin('monaco').use(new MonacoWebpackPlugin())
},
};
3.组件代码(在需要的地方引入这个)
<template>
<div class="container">
<div id="editor" style="height: 100%"></div> <!--宽高自行设定 -->
</div>
</template>
<script>
import * as monaco from 'monaco-editor'
export default {
name: "MonacoEditor.vue",
data() {
return {
editor: null
};
},
mounted() {
this.initHandler()
},
props:{
value: String,
options: { // 可配置属性 可扩展
type: Object,
default: () => {
return {
language:'javascript', // 语言
fontSize: 18, // 字号
};
}
}
},
methods: {
/**
* 数据加载
*/
initHandler() {
this.initEditor()
},
// 初始化编辑器,确保dom已经渲染
initEditor(){
// 编辑器配置项 参考文档https://microsoft.github.io/monaco-editor/api/modules/monaco.html
// 自定义灰色背景主题
monaco.editor.defineTheme('GreyTheme', {
base: 'vs',
inherit: true,
rules: [{ background: '#F9F9F9' }],
colors: {
// 相关颜色属性配置
'editor.background': '#F9F9F9', //背景色
}
});
//设置自定义主题
monaco.editor.setTheme('GreyTheme')
// 下面属性设置等同于官网DEMO效果
this.editor = monaco.editor.create(document.getElementById('editor'), {
value:this.value,//编辑器初始显示文字
language: this.options.language,//语言支持自行查阅demo
automaticLayout: false,//自动布局
theme:'GreyTheme', //官方自带三种主题vs, hc-black, or vs-dark
selectOnLineNumbers: true,//显示行号
roundedSelection: false,
readOnly: false, // 只读
cursorStyle: 'line', //光标样式
glyphMargin: true, //字形边缘
useTabStops: false,
fontSize: this.options.fontSize, //字体大小
autoIndent:false,//自动布局
renderWhitespace: 'all',
colorDecorators: true,
matchBrackets: 'always',
accessibilitySupport: 'on',
suggestions: true,
snippetSuggestions: 'top',
});
},
/**
* 获取编辑器值
* @returns {*}
*/
getValue(){
return this.editor.getValue(); //获取编辑器中的文本
}
},
destroyed(){
this.$emit('getEditorValue', this.editor.getValue())
}
}
</script>
<style scoped>
.monaco-mouse-cursor-text {
background: red !important;
}
</style>