Vue3+Vite中TinyMCE编辑器在Edit.vue首次加载不显示内容求助
问题解决:Vue3+Vite中TinyMCE编辑器在Edit页面首次加载不显示已有内容
问题场景
基于Vue3与Vite搭建的项目,封装了Editor.vue组件集成TinyMCE编辑器。该组件在Create.vue中可正常使用,能将内容保存至数据库,但在Edit.vue编辑数据时,编辑器首次加载无法显示已有内容,需刷新页面才能加载。
核心原因
Edit.vue的编辑数据通常通过异步请求获取,当TinyMCE编辑器初始化完成时,modelValue的异步数据还未返回,原代码中init事件调用editor.setContent(props.modelValue)时拿到的是空值。- 未监听
modelValue的后续变化,异步数据返回后编辑器无法自动同步内容。
解决方案
方案1:监听modelValue变化,实时更新编辑器内容
修改封装的Editor.vue,添加对modelValue的监听逻辑,移除无效的初始化手动赋值:
<template> <div class="mb-6"> <label class="block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2" :for="id"> {{ label }} <span class="text-red-600" v-if="isRequired">*</span> </label> <Editor ref="editorRef" :id="id" :value="modelValue" :api-key="apiKey" @change="$emit('update:modelValue', $event.level.content)" :init="editorInit" /> <ValidationMessage :validation="validation" :field="id" /> </div> </template> <script setup> import { ref, watch } from 'vue' import Editor from '@tinymce/tinymce-vue' import ValidationMessage from '@/components/ValidationMessage.vue' const apiKey = import.meta.env.VUE_APP_TINYMCE_API_KEY const props = defineProps({ isRequired: { type: Boolean, required: true }, label: { type: String, required: true }, id: { type: String, required: true }, modelValue: { type: String, required: true, default: '' }, validation: { type: Object, default: null, }, editorInit: { type: Object, default: () => ({ height: 500, selector: 'textarea', menubar: true, plugins: 'link image code lists', toolbar: 'undo redo | styleselect | forecolor | bold italic underline | alignleft aligncenter alignright alignjustify | outdent indent numlist bullist | link image | code', }), }, }) const editorRef = ref(null) // 监听modelValue变化,同步更新编辑器内容 watch(() => props.modelValue, (newVal) => { if (editorRef.value && newVal !== undefined) { editorRef.value.editor.setContent(newVal) } }, { immediate: true }) defineEmits(['update:modelValue']) </script>
方案2:延迟渲染Editor组件,等待异步数据加载完成
在Edit.vue中,确保数据加载完成后再渲染编辑器:
<template> <!-- 其他页面内容 --> <Editor v-if="course.fields.description" isRequired label="Deskripsi" id="description" v-model="course.fields.description" :validation="validation" /> <div v-else>加载中...</div> </template>
关键说明
- 移除原代码中
setupEditor的手动初始化赋值,@tinymce/tinymce-vue组件本身会通过valueprop初始化内容,但异步数据晚于组件初始化时,需要通过watch监听更新。 watch的immediate: true配置确保组件初始化时,若modelValue已有值能直接加载。
内容的提问来源于stack exchange,提问作者ASHafizullah
相关产品推荐
相关产品推荐

