0
点赞
收藏
分享

微信扫一扫

vue+monato-editor代码编辑高亮使用记录(组件化)

大漠雪关山月 2022-01-25 阅读 52

一、概念

二、使用步骤

  • 引用依赖
  • 找到webpack的配置文件(别弄到babel的配置文件里了,启动会造成babel的报错),我们这的webpack是分的多
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')
plugins: [
//HtmlWebpackPlugin别管,这里只是写例子,免得加这种数组不知道怎么加
        new HtmlWebpackPlugin({
            title: 'Message Bridge'
        }),
        new MonacoWebpackPlugin()
    ]
    

在这里插入图片描述

组件

在这里插入图片描述

<template>
  <div id="container" ></div> <!--宽高自行设定 -->
</template>

<script>
// 简化使用,不然得自己看需要什么,自己找在依赖中单个引用(这是个基本的总的)
import * as monaco from 'monaco-editor/esm/vs/editor/editor.main'
export default {
    props: {
      sql: {
        type: String,
        default () {
          return ''
        }
      }
    },
    data() {
        return {
            editor: null,
            mysql: ''
        }
    },
    watch: {
      sql(val) {
        console.log('sql');
        this.setValue(val)

      },
      mysql(val) {
        console.log('my', val);
        this.handleChange()
      }
    },
    mounted() {
      this.initEditor();
    },
    methods: {
        initEditor() {
             //  初始化编辑器,确保dom已经渲染
            this.editor = monaco.editor.create(document.getElementById('container'), {
                value: '', // 编辑器初始显示文字
                language: 'sql', // 语言支持自行查阅demo
                automaticLayout: true, // 自动布局
                theme: 'vs-dark' // 官方自带三种主题vs, hc-black, or vs-dark
            });
            this.setValue(this.sql)
            //monaco-editor原生内容变化事件监听设置
            this.editor.onDidChangeModelContent((event) => {
              const newValue = this.getValue();
              this.$emit('changeSql', newValue)
              })
            // document.getElementsByTagName('textarea')[0].value = this.sql
        },
        getValue() {
        //这个是plugin的方法,不然得项上面document那样自己从元素变化event的target下获取内容,麻烦
            return this.editor.getValue();
        },
        setValue(sql) {
        //这个是plugin的方法
            this.editor.setValue(sql);
        }
    }
}
</script>
//div无法直接高度为100%,得让所有父级设置高度
<style lang="scss" scoped>
#container {
  height: 97%;
}
</style>

举报

相关推荐

0 条评论