如何在 Monaco 编辑器中使用 setValue?
在 Monaco 编辑器中使用 setValue 方法可以更改编辑器中的文本内容。你可以通过以下步骤来实现这一点:
- 确保编辑器已初始化:在调用
setValue之前,确保编辑器实例已创建并且editor.value已被赋值。 - 调用
setValue方法:使用Monaco.editor.getModels()[0]?.setValue(code)来设置新的代码内容。
<template>
<div class="container">
<div class="code" ref="editorRef" />
</div>
</template>
<script lang="ts" setup>
import { onMounted, ref, watchEffect } from "vue"
import * as Monaco from "monaco-editor"
const editorRef = ref(null)
const props = defineProps({
code: {
type: String,
require: true
}
})
const editor = ref(null)
watchEffect(() => {
if (editor.value && props.code) {
const model = Monaco.editor.getModels()
model[0]?.setValue(props.code)
}
})
onMounted(() => {
if (editorRef.value !== null) {
editor.value = Monaco.editor.create(editorRef.value as HTMLElement, {
value: props.code,
language: "json",
theme: "vs-dark",
readOnly: props.readOnly,
formatOnPaste: true,
tabSize: 2,
minimap: {
enabled: false
}, // 是否启用预览图
acceptSuggestionOnEnter: "on",
autoClosingBrackets: "always", // 是否自动添加结束括号(包括中括号)
autoClosingQuotes: "always", // 是否自动添加结束的单引号 双引号
autoIndent: "brackets", // 是否自动缩进
folding: true, // 是否启用代码折叠
links: true, // 是否点击链接
scrollBeyondLastLine: false //设置编辑器是否可以滚动到最后一行之后
})
} else {
console.error("editorDom is not a DOM element")
}
})
</script>