vue2.x中使用monaco-editor
安装
注意两个库的版本指定
npm install monaco-editor@0.30.1 --save-devnpm install monaco-editor-webpack-plugin@6.0.0 --save-dev
配置
vue.config.js
中配置
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')module.exports = {configureWebpack: {plugins: [new MonacoWebpackPlugin()]}}
创建MonacoEditor
公共组件
<template><div ref="editorContainer" class="editor"></div></template><script>import * as monaco from 'monaco-editor';export default {name: 'MonacoEditor',data() {return {code: '',editor: null}},mounted() {this.init()},methods: {init() {// 初始化编辑器this.editor = monaco.editor.create(this.$refs.editorContainer, {value: this.code,language: 'javascript',tabSize: 2,scrollBeyondLastLine: false,automaticLayout: true, // 自动布局readOnly: false})console.log(this.editor)// 监听内容变化this.editor.onDidChangeModelContent(() => {})// 监听失去焦点事件this.editor.onDidBlurEditorText((e) => {console.log(e)});},// 获取编辑框内容getCodeContext() {return this.editor.getValue()},// 自动格式化代码format() {this.editor.trigger('anything', 'editor.action.formatDocument')// 或者// this.editor.getAction(['editor.action.formatDocument']).run()},changeEditor() {if (this.editor === null) {this.init()}const oldModel = this.editor.getModel()const newModel = monaco.editor.createModel(this.code,'javascript')if (oldModel) {oldModel.dispose()}this.editor.setModel(newModel)}}}</script><style scoped>.editor {width: 100%;min-height: 400px;}</style>
父组件中使用
<template><div><monaco-editor></monaco-editor></div></template><script>import MonacoEditor from '@/components/MonacoEditor'export default {name: 'Test6',components: {MonacoEditor}}</script>