Vue3中调用monaco-editor的getValue/setValue时编辑器卡顿问题求助
Vue3中monaco-editor调用getValue/setValue卡顿的原因及差异分析
在Vue3项目中使用monaco-editor时,若通过响应式ref对象调用getValue()或setValue()方法,编辑器会出现明显卡顿;但不调用这些方法时编辑器运行正常,却无法获取或设置编辑器内容。
原问题代码
<template> <div class="editor" ref="editorRef"></div> </template> <script setup lang="ts"> import * as monaco from 'monaco-editor' const code = ref('') const editorRef = ref<HTMLDivElement | null>(null) const editor = ref<monaco.editor.IStandaloneCodeEditor | null>(null) onMounted(() => { editor.value = monaco.editor.create(editorRef.value!, { value: code.value, language: 'javascript' }) editor.value.getModel()?.onDidChangeContent(() => (code.value = editor.value?.getValue() || '')) }) </script>
解决方法
使用Vue3提供的toRaw()API获取原始对象后,调用方法恢复正常:
const originEditor = toRaw(editor.value) originEditor.getValue() // 'Hello, World!' originEditor.setValue('Hello, Monaco!') // 执行成功
两种调用方式的差异
editor.value.getValue()卡顿的原因:editor是Vue的响应式ref对象,Vue会对ref包裹的实例对象生成Proxy代理。当调用代理对象的方法时,Proxy会拦截所有属性访问和方法调用流程,同时触发Vue的响应式追踪逻辑。而monaco-editor内部逻辑极为复杂,包含大量高频的属性读写、状态变更操作,每一步都经过Proxy拦截和响应式追踪会产生巨大的性能开销,最终导致编辑器卡顿。originEditor.getValue()运行正常的原因:toRaw()会返回响应式对象对应的原始未代理实例。直接调用原始对象的方法时,完全跳过Vue的Proxy拦截和响应式追踪,直接执行monaco-editor自身的原生逻辑,没有额外的性能损耗,因此运行流畅,方法调用也能正常完成。
额外说明:monaco-editor的实例本身不需要设置为响应式,我们只需要在特定时机获取或设置内容即可,因此将编辑器实例存储为普通变量,或通过toRaw()获取原始对象进行操作,都是更高效的方案。
内容的提问来源于stack exchange,提问作者Ziu
相关产品推荐
相关产品推荐

