Vue渲染函数用Quill结合Naive UI表格展开列的渲染问题
在Naive UI可展开表格中嵌入Quill富文本编辑器的渲染问题解决经验
在使用Naive UI实现带可展开列的表格时,尝试在展开列中展示Quill富文本编辑器时遇到了渲染异常:使用getElementById作为容器初始化Quill时,展开下方列的编辑器会错误渲染到上方已展开的列中。
问题原因
表格内部通过v-for循环生成多个展开列,导致DOM中出现重复的元素ID,而getElementById只会返回第一个匹配ID的元素,因此后续初始化的Quill实例会错误挂载到第一个容器上。
解决方法
改用Vue的ref获取组件内的容器元素,确保每个富文本编辑器实例都能绑定到当前组件对应的容器节点上,避免ID冲突带来的渲染错误。
相关代码
app.vue
{ type: 'expand', renderExpand: (rowExpand) => { return h('div',[h(RichTextEditor, { toolbar: [], content: rowExpand.content, theme: '', disable: true, } )]) } }
RichTextEditor.vue
<template> <div ref="richTextEditor" :style="{ height: height + 'px' }"> </div> </template> <script lang="ts"> import { defineComponent, onMounted, toRef, ref, } from '@vue/runtime-core' import Quill from 'quill' import 'quill/dist/quill.snow.css' import 'quill/dist/quill.bubble.css' export default defineComponent({ name: 'RichTextEditor', props: { height: { type: [Number, String], default: 'auto', }, theme: { type: String, default: 'snow' }, toolbar:{ type: Array, default: [ ['bold', 'italic', 'underline', 'strike'], ['blockquote', 'code-block'], [{ list: 'ordered' }, { list: 'bullet' }], [{ script: 'sub' }, { script: 'super' }], [{ indent: '-1' }, { indent: '+1' }], [{ direction: 'rtl' }], [{ size: ['small', false, 'large', 'huge'] }], [{ header: [1, 2, 3, 4, 5, 6, false] }], [{ color: [] }, { background: [] }], [{ align: [] }], ['link', 'image'], ['clean'], ] }, content:{ type: String, default: '' }, disable:{ type: Boolean, default: false } }, setup(props) { const theme = toRef(props,'theme') const toolbar = toRef(props,'toolbar') const content = toRef(props,'content') const disable = toRef(props,'disable') const richTextEditor = ref() let quill: Quill | null = null const init = () => { const options = { modules: { toolbar: toolbar.value, }, placeholder: '请输入文章内容…', theme: theme.value, readOnly: disable.value, } // 原错误写法:quill = new Quill(document.getElementById('richTextEditor') as Element, options) // 使用getElementById会导致渲染到错误的列中 quill = new Quill(richTextEditor.value as Element, options) if(content.value !== ''){ quill?.setContents(JSON.parse(content.value)) } } onMounted(init) const getHtmlContent = () => { return (richTextEditor.value?.firstChild as any).innerHTML } const getJsonContent = () => { return JSON.stringify(quill?.getContents()) } const setContents = (content: any) => { console.log(content) quill?.setContents(JSON.parse(content)) } return { richTextEditor, getHtmlContent, getJsonContent, setContents, } }, }) </script>
注:我是Vue和JavaScript新手,若有错误欢迎指正。
内容的提问来源于stack exchange,提问作者ilok
相关产品推荐
相关产品推荐

