|
@@ -8,33 +8,28 @@ import * as monaco from 'monaco-editor';
|
|
|
|
|
|
const props = defineProps({
|
|
|
modelValue: String, // v-model 绑定
|
|
|
- value: String, // 传统 value 绑定(兼容旧代码)
|
|
|
+ value: String, // 兼容传统 value 绑定
|
|
|
language: String,
|
|
|
});
|
|
|
|
|
|
-const emit = defineEmits([
|
|
|
- 'update:modelValue', // v-model 更新事件
|
|
|
- 'change', // 传统 change 事件
|
|
|
-]);
|
|
|
+const emit = defineEmits(['update:modelValue', 'change']);
|
|
|
|
|
|
const editor = ref(null);
|
|
|
+let isUpdatingFromParent = false; // 添加防止死循环的锁
|
|
|
|
|
|
-// 获取当前绑定的值(优先使用 modelValue)
|
|
|
-const getCurrentValue = () => {
|
|
|
- return props.modelValue ?? props.value;
|
|
|
-};
|
|
|
+// 获取当前值
|
|
|
+const getCurrentValue = () => props.modelValue ?? props.value;
|
|
|
+const getEditorValue = () => toRaw(editor.value)?.getValue() || '';
|
|
|
|
|
|
-// 获取编辑器内容
|
|
|
-const getEditorValue = () => {
|
|
|
- return toRaw(editor.value)?.getValue() || '';
|
|
|
-};
|
|
|
-
|
|
|
-// 监听外部值变化(如果父组件修改了 value,同步到编辑器)
|
|
|
+// 监听父组件传来的值变化(用于外部更新编辑器)
|
|
|
watch(
|
|
|
() => getCurrentValue(),
|
|
|
(newValue) => {
|
|
|
- if (editor.value && newValue !== getEditorValue()) {
|
|
|
- editor.value.setValue(newValue);
|
|
|
+ const editorVal = getEditorValue();
|
|
|
+ if (editor.value && newValue !== editorVal) {
|
|
|
+ isUpdatingFromParent = true; // 开锁,标记是外部更新
|
|
|
+ editor.value.setValue(newValue || '');
|
|
|
+ isUpdatingFromParent = false;
|
|
|
}
|
|
|
}
|
|
|
);
|
|
@@ -59,17 +54,19 @@ onMounted(() => {
|
|
|
automaticLayout: true,
|
|
|
});
|
|
|
|
|
|
- // 监听编辑器内容变化
|
|
|
+ // 编辑器内容变化时触发
|
|
|
editor.value.onDidChangeModelContent(() => {
|
|
|
+ if (isUpdatingFromParent) return; // 阻止外部设置引起的触发
|
|
|
+
|
|
|
const newValue = getEditorValue();
|
|
|
- emit('update:modelValue', newValue); // 触发 v-model 更新
|
|
|
- emit('change', newValue); // 触发传统 change 事件
|
|
|
+ emit('update:modelValue', newValue); // 通知父组件更新
|
|
|
+ emit('change', newValue);
|
|
|
});
|
|
|
});
|
|
|
</script>
|
|
|
|
|
|
<style>
|
|
|
-#editorContainer{
|
|
|
+#editorContainer {
|
|
|
height: 400px !important;
|
|
|
}
|
|
|
</style>
|