开发者问题收集

使用 Vue.js 3 在 QuillJS 编辑器中删除文本时出错:未捕获的类型错误:无法读取 null 的属性(读取“偏移量”)

2024-03-20
405

我在 Vue.js 3 项目( option API )上初始化了 QuillJS 编辑器,以下是组件中的代码:

<script>
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import Quill from 'quill'

export default {
  name: 'AppChatContainer',
  components: { FontAwesomeIcon },
  props: {
    messages: {
      type: Array,
      required: true,
      default: () => []
    },
    isSending: {
      type: Boolean,
      default: false
    }
  },

  emits: ['new-message'],

  data() {
    return {
      quill: null
    }
  },

  mounted() {
    this.quill = new Quill('#message', {
      theme: 'bubble',
      modules: {
        toolbar: [
          ['bold', 'italic', { color: [] }],
          [{ list: 'ordered' }, { list: 'bullet' }]
        ]
      }
    })
  },

  methods: {
    handleSubmission() {
      const message = this.quill.getContents()
      this.$emit('new-message', message)
      // this.quill.setContents([{ insert: '\n' }]) // <= Error here
      // this.quill.setText('') // <= Error here
      this.quill.deleteText(0, this.quill.getLength()) // <= Error here
    },

    convertDeltaToHtml(delta) {
      const tempQuill = new Quill(document.createElement('div'))
      tempQuill.setContents(delta)
      return tempQuill.root.innerHTML
    }
  }
}
</script>

<template>
  <form class="h-100 position-relative" @submit.prevent="handleSubmission">
    <div class="flex-grow-1 overflow-y-scroll">
      <div
        v-for="message in messages"
        :key="message.id"
        :class="`message mb-4 ${message.isAuthor ? 'author' : ''} ${message.isSending ? 'sending' : ''}`"
      >
        <div class="content" v-html="convertDeltaToHtml(message.content)" />
        <small v-if="message.isSending" class="text-gray-700 fw-light d-block mt-1 ms-2 me-3">
          Envois en cours...
        </small>
        <small v-else class="text-gray-700 fw-light d-block mt-1 ms-2 me-3">
          {{ message.isAuthor ? 'Vous' : message.authorName }}, le {{ message.date }}</small
        >
      </div>
    </div>
    <div class="message-container">
      <div id="message" />
      <button type="submit" class="btn btn-amsom-green" :disabled="isSending">
        <font-awesome-icon v-if="!isSending" icon="paper-plane" />
        <div v-else class="spinner-border spinner-border-sm" role="status">
          <span class="visually-hidden">Envois en cours...</span>
        </div>
      </button>
    </div>
  </form>
</template>

<style scoped>
// ...
</style>

当我提交表单时,会调用 handleSubmission() 方法。当我尝试删除编辑器内容时出现此错误:

Uncaught TypeError: Cannot read properties of null (reading 'offset')
    at quill.js?v=b3144345:12600:26
    at Array.map (<anonymous>)
    at Proxy.normalizedToRange (quill.js?v=b3144345:12597:31)
    at Proxy.getRange (quill.js?v=b3144345:12586:25)
    at Proxy.update (quill.js?v=b3144345:12723:43)
    at Proxy.update (quill.js?v=b3144345:13796:20)
    at Proxy.getSelection (quill.js?v=b3144345:13690:10)
    at Proxy.modify (quill.js?v=b3144345:13906:44)
    at Proxy.deleteText (quill.js?v=b3144345:13553:19)
    at Proxy.handleSubmission (AppChatContainer.vue:47:18)

我尝试了几种从编辑器中删除内容的方法,但总是遇到同样的问题……

handleSubmission() {
      const message = this.quill.getContents()
      this.$emit('new-message', message)
      // this.quill.setContents([{ insert: '\n' }])
      // this.quill.setText('');
      this.quill.deleteText(0, this.quill.getLength())
    },
2个回答

尝试这个微小的包装器组件,您可以在其上构建您的编辑器:

npm add [email protected] vue-quilly
# Or
pnpm add [email protected] vue-quilly

如果您需要所有模块,请导入 Quill 完整构建,或者使用最少所需模块的 核心构建

import Quill from 'quill' // Full build
import Quill from 'quill/core' // Core build
import { QuillyEditor } from 'vue-quilly'

添加核心样式。另外,如果需要,请导入 Quill 的 主题 之一:

import 'quill/dist/quill.core.css' // Required
import 'quill/dist/quill.snow.css' // For snow theme (optional)
import 'quill/dist/quill.bubble.css' // For bubble theme (optional)

定义 Quill 选项

const options = {
  theme: 'snow', // If you need Quill theme
  modules: {
    toolbar: true,
  },
  placeholder: 'Compose an epic...',
  readOnly: false
}

初始化编辑器:

const editor = ref<InstanceType<typeof QuillyEditor>>()
const model = ref<string>('<p>Hello Quilly!</p>')
// Quill instance
let quill: Quill | null = null
onMounted(() => {
  quill = editor.value?.initialize(Quill)!
})
<QuillyEditor
  ref="editor"
  v-model="model"
  :options="options"
  @text-change="({ delta, oldContent, source }) => console.log('text-change', delta, oldContent, source)"
  @selection-change="({ range, oldRange, source }) => console.log('selection-change', range, oldRange, source)"
  @editor-change="(eventName) => console.log('editor-change', `eventName: ${eventName}`)"
  @focus="(quill) => console.log('focus', quill)"
  @blur="(quill) => console.log('blur', quill)"
  @ready="(quill) => console.log('ready', quill)"
/>

使用 v-model 作为 HTML 内容类型。您可以使用 Quill 实例以 Delta 格式设置内容:

quill?.setContents(
  new Delta()
    .insert('Hello')
    .insert('\n', { header: 1 })
    .insert('Some ')
    .insert('initial', { bold: true })
    .insert(' ')
    .insert('content', { underline: true })
    .insert('\n')
)

使用 QullyEditor 创建编辑器 demo

alekswebnet
2024-04-27

我找到了一个解决方案,但我不认为这是从编辑器中删除内容的好方法:

handleSubmission() {
      const message = this.quill.getContents()
      this.$emit('new-message', message)
      this.quill.root.innerHTML = ''
    },

我使用了 this.quill.root.innerHTML = ''

LuckyFox
2024-03-20