You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3拆分TinyMCE编辑器组件后值无法更新的问题

问题原因与解决方案

问题出在你直接将props的modelValue绑定到TinyMCE的v-model,违反了Vue单向数据流规则,同时@input事件传递的是未更新的props值,导致父组件无法同步编辑器的最新内容。此外,editorInit中的selector配置是多余的,会干扰tinymce-vue组件的正常初始化。

修复步骤

1. 修改子组件Editor.vue的脚本部分

引入Vue的响应式API,用本地变量代理props值,并监听props变化同步更新:

<script setup>
import { ref, watch } from 'vue'
import Editor from '@tinymce/tinymce-vue'
import ValidationMessage from '@/components/ValidationMessage'

const apiKey = process.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: false,
        default: ''
    },
    validation: {
        type: Object,
        default: null,
    },
    editorInit: {
        type: Object,
        default: () => ({
            height: 500,
            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 emit = defineEmits(['update:modelValue'])

// 本地响应式变量,存储编辑器当前值
const localValue = ref(props.modelValue)

// 监听父组件传入的modelValue变化,同步到本地变量
watch(() => props.modelValue, (newVal) => {
    localValue.value = newVal
})

// 编辑器内容变化时,向父组件发送更新事件
const handleInput = () => {
    emit('update:modelValue', localValue.value)
}
</script>

2. 更新模板中的绑定

将TinyMCE组件的v-model绑定到本地变量,并使用自定义的输入事件处理函数:

<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 
            :id="id" 
            v-model="localValue" 
            :api-key="apiKey" 
            @input="handleInput"
            :init="editorInit" 
        />
        <ValidationMessage :validation="validation" :field="id" />
    </div>
</template>

关键说明

  • 本地变量代理:Vue中props是只读的,直接绑定到可输入组件的v-model会导致修改无法同步,必须用本地响应式变量中转。
  • 移除selector:tinymce-vue组件会自动生成对应的DOM元素,手动设置selector会导致组件无法正确识别编辑器实例。
  • 响应式同步:通过watch监听父组件传入的modelValue,确保父组件主动更新值时,编辑器能同步显示最新内容。

内容的提问来源于stack exchange,提问作者ASHafizullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:53:12