600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > monaco-editor vue2.X组件化

monaco-editor vue2.X组件化

时间:2023-11-29 12:48:16

相关推荐

monaco-editor vue2.X组件化

安装

指定版本安装(版本过高容易报错)

npm install monaco-editor@0.30.1 npm install monaco-editor-webpack-plugin@6.0.0 --save-dev

配置

vue.config.js中配置monaco-editor-webpack-plugin

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')module.exports = {configureWebpack: {plugins: [new MonacoWebpackPlugin()]}}

创建MonacoEditor公共组件

<template><div ref="editor" 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.editor, {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,'sql')if (oldModel) {oldModel.dispose()}this.editor.setModel(newModel)}}}</script><style scoped>.editor {width: 100%;min-height: 100%;}</style>

父组件使用

<template><div><monaco-editor></monaco-editor></div></template><script>import MonacoEditor from '@/components/MonacoEditor'export default {name: 'Father',components: {MonacoEditor}}</script>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。