vue2.x中monaco-editor的使用
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-edit
·
vue2.x中使用monaco-editor
安装
注意两个库的版本指定
npm install monaco-editor@0.30.1 --save-dev
npm 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>
更多推荐
已为社区贡献31条内容
所有评论(0)