|
@@ -1,54 +1,70 @@
|
|
|
<template>
|
|
|
- <div id="editorContainer" ></div>
|
|
|
+ <div id="editorContainer"></div>
|
|
|
</template>
|
|
|
|
|
|
<script setup>
|
|
|
-import { toRaw } from 'vue';
|
|
|
-import * as monaco from 'monaco-editor'; // 全部导入
|
|
|
+import { ref, onMounted, watch, toRaw } from 'vue';
|
|
|
+import * as monaco from 'monaco-editor';
|
|
|
|
|
|
const props = defineProps({
|
|
|
- value: String,
|
|
|
+ modelValue: String, // v-model 绑定
|
|
|
+ value: String, // 传统 value 绑定(兼容旧代码)
|
|
|
language: String,
|
|
|
});
|
|
|
|
|
|
-const getVal = () => {
|
|
|
- return toRaw(editor.value).getValue(); //获取编辑器中的文本
|
|
|
-}
|
|
|
-
|
|
|
-const emit = defineEmits(['change']);
|
|
|
+const emit = defineEmits([
|
|
|
+ 'update:modelValue', // v-model 更新事件
|
|
|
+ 'change', // 传统 change 事件
|
|
|
+]);
|
|
|
|
|
|
const editor = ref(null);
|
|
|
|
|
|
+// 获取当前绑定的值(优先使用 modelValue)
|
|
|
+const getCurrentValue = () => {
|
|
|
+ return props.modelValue ?? props.value;
|
|
|
+};
|
|
|
+
|
|
|
+// 获取编辑器内容
|
|
|
+const getEditorValue = () => {
|
|
|
+ return toRaw(editor.value)?.getValue() || '';
|
|
|
+};
|
|
|
+
|
|
|
+// 监听外部值变化(如果父组件修改了 value,同步到编辑器)
|
|
|
+watch(
|
|
|
+ () => getCurrentValue(),
|
|
|
+ (newValue) => {
|
|
|
+ if (editor.value && newValue !== getEditorValue()) {
|
|
|
+ editor.value.setValue(newValue);
|
|
|
+ }
|
|
|
+ }
|
|
|
+);
|
|
|
+
|
|
|
onMounted(() => {
|
|
|
monaco.editor.defineTheme("custom-light", {
|
|
|
- base: "vs", // 基于白色主题
|
|
|
+ base: "vs",
|
|
|
inherit: true,
|
|
|
rules: [],
|
|
|
colors: {
|
|
|
- "editorGutter.background": "#EEEEEE", // 设置行号栏背景为灰色
|
|
|
+ "editorGutter.background": "#EEEEEE",
|
|
|
},
|
|
|
});
|
|
|
|
|
|
editor.value = monaco.editor.create(document.getElementById('editorContainer'), {
|
|
|
- value: props.value || '',
|
|
|
+ value: getCurrentValue() || '',
|
|
|
language: props.language || 'python',
|
|
|
- minimap: {
|
|
|
- enabled: true,
|
|
|
- },
|
|
|
- colorDecorators: true, // 颜色装饰器
|
|
|
- readOnly: false, // 是否开启已读功能
|
|
|
- theme: "custom-light", // 主题 vs hc-black
|
|
|
+ minimap: { enabled: true },
|
|
|
+ colorDecorators: true,
|
|
|
+ readOnly: false,
|
|
|
+ theme: "custom-light",
|
|
|
automaticLayout: true,
|
|
|
});
|
|
|
|
|
|
// 监听编辑器内容变化
|
|
|
editor.value.onDidChangeModelContent(() => {
|
|
|
- // 触发父组件的 change 事件,通知编辑器内容变化
|
|
|
- emit('change', getVal());
|
|
|
+ const newValue = getEditorValue();
|
|
|
+ emit('update:modelValue', newValue); // 触发 v-model 更新
|
|
|
+ emit('change', newValue); // 触发传统 change 事件
|
|
|
});
|
|
|
-
|
|
|
- // 启用代码检查
|
|
|
- // enableCodeValidation();
|
|
|
});
|
|
|
</script>
|
|
|
|