4

I'm trying to use tiptap with Vue.js with the <script setup> approach of creating a Single File Component (SFC).

TextEditor.vue

<template>
  <editor-content :editor="editor" class="editor" />
</template>

<script lang="ts" 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({
  content: props.modelValue,
  extensions: [StarterKit],
  onUpdate: ({editor}) => {
    let content = editor.getHTML()
    emit('update:modelValue', content)
  }
})
</script>

I then use this component like this:

<template>
  <text-editor v-model="myModel.content" />
</template>

This works when <text-editor> is loaded after myModel.content is defined.

However, if <text-editor> loads before myModel.content is set from my database API, then the text content remains blank. From what I understand from looking at the examples in the tiptap docs, I need to somehow use watch to update my editor when props.modelValue is changed using something like this:

watch(() => props.modelValue, (newValue, oldValue) => {
  const isSame = newValue === oldValue
  console.log(`Same: ${isSame}`)
  if (isSame) {
    return
  }
  editor.commands.setContent(newValue, false)
})

However, in the snippet above, editor is a ShallowRef type and doesn't have a reference to commands to call setContent.

What is the best way to get the above example to work when loading tiptap with the <script setup> approach?

3
  • Are your myModel.content is a Ref ? Commented Jun 8, 2022 at 16:52
  • 1
    If it's ok, you can show the editor only when the data is ready by adding a v-if: <text-editor v-if="myModel.content" v-model="myModel.content" />. Commented Jun 9, 2022 at 3:31
  • You shouldn't compare newValue === oldValue as it results to false when the change come from the editor (and triggers uselessly setContent). It's better to track changes with editor.value.getHTML() === newValue. Commented Jan 27, 2023 at 8:56

1 Answer 1

10

You need to access the ref actual value with .value

editor.value?.commands.setContent('<p>test</p>', false)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.