记录在 Vue 3 中使用 @monaco-editor/vue
时,遇到响应式丢失或内容无法正常更新的情况及处理方法。
一、问题现象
- 编辑器初始化正常,但外部变量变化后编辑器内容不更新
- 通过代码修改
v-model:value
绑定的值,编辑器内文本不变 - 编辑器输入内容后,外部变量未同步更新
二、问题原因
@monaco-editor/vue
的v-model:value
绑定是单向初始化- 第一次加载时会写入值
- 之后如果外部变量更新,不会自动覆盖编辑器内容(为避免用户编辑被覆盖)
响应式对象直接传递给编辑器组件
- 若是
ref
/reactive
包裹对象,需要解构成普通字符串,否则内部不会触发重新渲染
- 若是
onChange
回调未正确处理- 编辑器内容变化需要手动同步到外部变量
三、正确的绑定方式
<script setup>
import { ref } from 'vue'
import MonacoEditor from '@monaco-editor/vue'
const code = ref('// 初始内容')
function handleChange(value) {
code.value = value
}
</script>
<template>
<MonacoEditor
height="500px"
language="javascript"
:value="code"
@change="handleChange"
/>
</template>
四、如果需要外部变量强制刷新编辑器内容
@monaco-editor/vue
暴露了 editor
实例,可手动更新:
<script setup>
import { ref, watch } from 'vue'
import MonacoEditor from '@monaco-editor/vue'
const code = ref('// 初始内容')
let editorInstance = null
function handleMount(editor) {
editorInstance = editor
}
watch(code, (newVal) => {
if (editorInstance && editorInstance.getValue() !== newVal) {
editorInstance.setValue(newVal)
}
})
</script>
<template>
<MonacoEditor
height="500px"
language="javascript"
:value="code"
@mount="handleMount"
/>
</template>
五、小结
v-model:value
在该库中不是双向绑定,需要手动维护同步- 外部变量更新 → 强制
setValue
- 内部编辑 → 通过
@change
回调更新变量