vue3中使用monaco-editor

第一步

	npm i monaco-editor@0.34.1 monaco-editor-webpack-plugin@7.0.1

第二步

// 随便找一个页面里都可以
<template>
  <!-- <button @click="format">格式化</button> -->
  <button @click="getCodeContext">获取数据</button>
  <button @click="handleTheme">设置主题</button>
  <div id="app" ref="editorContainer"></div>
</template>

<script setup lang="ts">
import { onMounted, ref, toRaw } from "vue";
import * as monaco from "monaco-editor";
const codeContent = ref("");

const editorContainer = ref<any>(null);
const editor = ref<any>(null);
const editorTheme = ref<string>("vs-dark");
onMounted(() => {
  editor.value = monaco.editor.create(editorContainer.value, {
    value: "",
    theme: editorTheme.value, // 主题
    language: "javascript",
    folding: true, // 是否折叠
    foldingHighlight: true, // 折叠等高线
    foldingStrategy: "indentation", // 折叠方式  auto | indentation
    showFoldingControls: "always", // 是否一直显示折叠 always | mouseover
    disableLayerHinting: true, // 等宽优化
    emptySelectionClipboard: false, // 空选择剪切板
    selectionClipboard: false, // 选择剪切板
    automaticLayout: true, // 自动布局
    codeLens: false, // 代码镜头
    scrollBeyondLastLine: false, // 滚动完最后一行后再滚动一屏幕
    colorDecorators: true, // 颜色装饰器
    accessibilitySupport: "off", // 辅助功能支持  "auto" | "off" | "on"
    lineNumbers: "on", // 行号 取值: "on" | "off" | "relative" | "interval" | function
    lineNumbersMinChars: 5, // 行号最小字符   number
    readOnly: false, //是否只读  取值 true | false
  });
  // 监听内容变化
  editor.value.onDidChangeModelContent((e) => {});
  console.log(editor.value, "监听内容变化");
  // 监听失去焦点事件
  editor.value.onDidBlurEditorText(() => {});
});
// 获取编辑框内容
function getCodeContext() {
  codeContent.value = toRaw(editor.value).getValue();
  return console.log(codeContent.value);
}
// 自动格式化代码
function format() {
  toRaw(editor.value).trigger("anything", "editor.action.formatDocument");
  // 或者
  // this.editor.getAction(['editor.action.formatDocument']).run()
}
// 修改主题
function handleTheme() {
  monaco.editor.setTheme("vs");
}
</script>

<style scoped>
#app {
  height: 500px;
}
</style>

第三步

// vue.config.js 配置代码提示插件
const { defineConfig } = require("@vue/cli-service");
const MonacoWebpackPlugin = require("monaco-editor-webpack-plugin");
module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: {
    plugins: [new MonacoWebpackPlugin()],
  },
});

你可能感兴趣的:(javascript,vue.js,前端)