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

Vue中如何实现TinyMCE组件与父组件的数据传递及更新

解决Vue父子组件TinyMCE内容同步问题

你用props没成功是因为Vue的props是单向数据流,子组件不能直接修改props的值,正确的做法是通过自定义事件或Vue的v-model语法糖实现双向数据传递,以下是具体修改方案:

1. 修改子组件 TinyMCE.vue

监听TinyMCE编辑器的内容变化,将更新后的内容通过事件传递给父组件:

<template>
  <div>
    <p>This will be Editor JS</p>
    <div name="editor">
      <Editor
        api-key=""
        :init="{
          plugins: 'lists link image table code help wordcount'
        }"
        :model-value="modelValue"
        @input="(val) => emit('update:modelValue', val)"
      />
    </div>
  </div>
</template>

<script setup>
import Editor from '@tinymce/tinymce-vue'

// 接收父组件传递的初始内容
const props = defineProps({
  modelValue: String
})

// 定义向父组件发送内容更新的事件
const emit = defineEmits(['update:modelValue'])
</script>

<style lang="scss" scoped></style>

2. 修改父组件 TestComponent.vue

通过v-model绑定响应式变量,实现与子组件的内容同步:

<template>
  <div class="h-screen flex w-screen flex-col items-center justify-center gap-5">
    <div>hello from test</div>
    <div class="h-[300px] w-[300px]">
      <!-- 用v-model绑定text,自动同步编辑器内容 -->
      <TinyMCE v-model="text"></TinyMCE>
      <div
        name="result"
        class="flex h-[300px] w-[300px] items-center justify-center border-2 border-black"
        v-html="text"
      ></div>
    </div>
  </div>
</template>

<script setup>
import TinyMCE from './TinyMCE.vue'
import { ref } from 'vue'
const text = ref('')
</script>

<style lang="scss" scoped></style>

原理说明

Vue组件上的v-model是语法糖,等价于:model-value="text"和@update:model-value="text = $event"。子组件通过defineProps接收父组件的初始值,通过defineEmits发送内容更新事件,父组件监听事件并更新自身响应式变量,最终实现双向数据同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 16:30:07