如何在 Vue 3 脚本设置中将 TipTap 绑定到父 v-model?

Art*_*nov 4 javascript rich-text-editor vue.js vuejs3 tiptap

我试图用作tiptap子组件并将其内容传递给父组件,v-model但tiptap的文档似乎只提供了如何在没有 的情况下执行此操作的信息script setup,它使用不同的API。

这是我的parent组件:

<template>
    <cms-custom-editor v-model:modelValue="state.content"/>
    <p>{{state.content}}</p>
</template>


<script setup>
import CmsCustomEditor from '../../components/backend/cms-custom-editor.vue'
import {reactive} from "vue";

const state = reactive({
    content: '<p>A Vue.js wrapper component for tiptap to use <code>v-model</code>.</p>',
})

</script>
Run Code Online (Sandbox Code Playgroud)

这个child组件具有tiptap

<template>
  <div id="cms-custom-editor" class="cms-custom-editor">
    <editor-content :editor="editor"/>
  </div>
</template>


<script setup>
import {useEditor, EditorContent} from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'

const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['update:modelValue'])

const editor = useEditor({
    extensions: [StarterKit],
    content: props.modelValue,
    onUpdate: () => {
        emit('update:modelValue', editor.getHTML())
    }
})
</script>
Run Code Online (Sandbox Code Playgroud)

一旦我在编辑器字段中输入内容,此代码行就会失败:

emit('update:modelValue', editor.getHTML())
Run Code Online (Sandbox Code Playgroud)

并抛出此错误:

Uncaught TypeError: editor.getHTML is not a function
    at Editor2.onUpdate (cms-custom-editor.vue?t=1654253729389:28:42)
    at chunk-RCTGLYYN.js?v=89d16c61:11965:48
    at Array.forEach (<anonymous>)
    at Editor2.emit (chunk-RCTGLYYN.js?v=89d16c61:11965:17)
    at Editor2.dispatchTransaction (chunk-RCTGLYYN.js?v=89d16c61:12252:10)
    at EditorView.dispatch (chunk-RCTGLYYN.js?v=89d16c61:9138:27)
    at readDOMChange (chunk-RCTGLYYN.js?v=89d16c61:8813:8)
    at DOMObserver.handleDOMChange (chunk-RCTGLYYN.js?v=89d16c61:8924:77)
    at DOMObserver.flush (chunk-RCTGLYYN.js?v=89d16c61:8575:12)
    at DOMObserver.observer (chunk-RCTGLYYN.js?v=89d16c61:8455:14)
Run Code Online (Sandbox Code Playgroud)

我使用了文档中的方法(第 5 章 v-model),正如我所说,它不是为script setup.

Art*_*nov 12

伙计,文档很混乱。他们混合了标准composition apiscript setup. 无论如何,这就是它的工作原理:

const editor = useEditor({
    extensions: [StarterKit],
    content: props.modelValue,
    onUpdate: ({editor}) => {
        emit('update:modelValue', editor.getHTML())
    }
})
Run Code Online (Sandbox Code Playgroud)

  • @HonestKnight,以防您仍然需要它:您可能必须定义发射,如: const emmit = DefineEmits(['update:modelValue']) (2认同)