大家好,我是作曲家种太阳,很久不见
Monaco Editor 可以算的上前端的一个强大的编辑器神器,希望你有所了解
按照步骤来,你可以完成一个monaco在线编辑器的demo,更多APi需要在官网上去查阅~
介绍
Monaco Editor是为VS Code提供支持的代码编辑器,运行在浏览器环境中。编辑器提供代码提示,智能建议等功能。供开发人员远程更方便的编写代码。移动浏览器或移动Web框架不支持Monaco编辑器。简单的理解就是VSCode中的代码编辑器和Monaco Editor使用的很多相同的核心模块,你可以将Monaco Editor用到自己的项目中,作为云端编辑器的支持,支持IE 11,Edge,Chrome,Firefox,Safari和Opera!\
monaco相关地址
Github:
文档和示例等:
1.安装
在package.json的dependencies中加入,并且npm install 安装
"monaco-editor": "^0.29.1",
"monaco-editor-webpack-plugin": "^5.0.0"
2.使用插件
(1)在vue.config.js引入
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')
(1.1)vue.config.js的chainWebpack中
config.plugin('monaco-editor').use(MonacoWebpackPlugin, [
{
// Languages are loaded on demand at runtime
languages: ['json', 'javascript', 'html', 'xml']
}
])
3.封装vue通用monaco编辑器组件
组件中的props.types支持多种格式(TypeScript, JavaScript, CSS, LESS, SCSS, JSON, HTML,sql)等
<template>
<div id="monaco-editor-box" >
<div id="monaco-editor" ref="monacoEditor" />
</div>
</template>
<script>
import * as monaco from "monaco-editor/esm/vs/editor/editor.main";
export default {
name:"MonacoEditor",
components: {},
props: {
// 编辑器支持的文本格式,自行在百度上搜索
types: {
type: String,
default:"json"
},
// 名称
name: {
type: String,
default:"test"
},
editorOptions: {
type: Object,
default: function () {
return {
selectOnLineNumbers: true,
roundedSelection: false,
readOnly: false, // 只读
writeOnly: false,
cursorStyle: "line", //光标样式
automaticLayout: true, //自动布局
glyphMargin: true, //字形边缘
useTabStops: false,
fontSize: 32, //字体大小
autoIndent: true, //自动布局
//quickSuggestionsDelay: 500, //代码提示延时
};
},
},
codes: {
type: String,
default: function () {
return "";
},
},
},
data() {
return {
editor: null, //文本编辑器
isSave: true, //文件改动状态,是否保存
codeValue: null, //保存后的文本
};
},
watch: {
codes: function (newValue) {
console.debug("Code editor: content change");
if (this.editor) {
if (newValue !== this.editor.getValue()) {
this.editor.setValue(newValue);
this.editor.trigger(this.editor.getValue(), 'editor.action.formatDocument')
}
}
}
},
mounted() {
this.initEditor();
},
methods: {
initEditor() {
const self = this;
// 初始化编辑器,确保dom已经渲染
this.editor = monaco.editor.create(self.$refs.monacoEditor, {
value: self.codeValue || self.codes, // 编辑器初始显示内容
language: self.types, // 支持语言
theme: "vs-light", // 主题
selectOnLineNumbers: true, //显示行号
editorOptions: self.editorOptions,
});
// self.$emit("onMounted", self.editor); //编辑器创建完成回调
self.editor.onDidChangeModelContent(function (event) {
//编辑器内容changge事件
self.codesCopy = self.editor.getValue();
self.$emit("onCodeChange", self.editor.getValue(), event);
});
},
},
};
</script>
<style scoped>
#monaco-editor {
width: 100%;
height: 600px;
}
</style>
4.使用组件
<template>
<monaco-editor
@onCodeChange="excelTextChanged" types="text" :codes="textarea">
</monaco-editor>
</template>
data:{
textarea:""
}
methods: {
excelTextChanged(text){
console.log("text",text)
this.textarea = text
},
}