最近修改公司模版,富文本内可以插入表格,选择了几款,最终确定使用quill+quill-better-table,
quill 2.0版本的表格功能比较弱,故所需要quill-better-table插件的协助来完成该需求。
需求如下:
点击富文本记录光标位置,选择左侧可以将内容插入记录的光标位置。同时支持插入表格,表格编辑功能。
安装
-
npm install quill ^2.0.0-dev.3 版本需要大于2.0版本
-
npm install quill-better-table
封装富文本组件:
editor.vue
<template>
<div>
<div class="editor"></div>
</div>
</template>
<script>
import Quill from 'quill'
import 'quill/dist/quill.snow.css'
import QuillBetterTable from 'quill-better-table'
import 'quill-better-table/dist/quill-better-table.css'
Quill.register({
'modules/better-table': QuillBetterTable
}, true)
export default {
name: 'editor',
props: ['value'],
data() {
return {
quill: null,
content:'',
options: {
theme: 'snow',
modules: {
toolbar: {
container: [
['bold', 'italic', 'underline', 'strike'],
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'script': 'super' }],
[{ 'indent': '-1' }, { 'indent': '+1' }],
[{ 'size': ['small', false, 'large', 'huge'] }],
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }],
[{ 'align': [] }],
['link', 'image'],
[
{ 'table': 'TD' },
],
],
handlers: {
'table': function () {
this.quill.getModule('better-table').insertTable(3, 3)
},
},
},
table: false,
'better-table': {
operationMenu: {
items: {
unmergeCells: {
text: 'Another unmerge cells name'
}
},
background: {
color: '#333'
},
color: {
colors: ['green', 'red', 'yellow', 'blue', 'white'],
text: 'background:'
}
}
},
keyboard: {
bindings: QuillBetterTable.keyboardBindings
}
},
placeholder: 'Insert text here ...'
}
}
},
mounted() {
let dom = this.$el.querySelector('.editor')
this.quill = new Quill(dom, this.options);
this.quill.setContents(this.value)
this.quill.on('text-change', () => {
this.$emit('input', this.quill.getContents())
});
// this.quill.on('text-change', () => {
// this.$emit('input', this.quill.root.innerHTML)
// })
}
}
</script>
父组件引用:
import ckeditor from '@/components/common/editor'
<ckeditor class='quillEditorChild' ref='myQuillEditor' v-model="ContentArea" @input="onEditorChange($event)"> </ckeditor>
渲染:
原有思路是打算通过this.$refs.myQuillEditor.quill.root.innerHTML获取html数据,后来发现html绑定在富文本无法渲染,看官网文档需要通过getContens获取delta数据,同时渲染也是将delta数据,通过quill.setContents(delta)。富文本会自动将delta格式数据解析成dom将内容展示出来。
Delta 是JSON的一个子集,只包含一个 ops 属性,它的值是一个对象数组,每个数组项代表对编辑器的一个操作。
delta格式如下:
{
ops: [
{ insert: 'Gandalf', attributes: { bold: true } },
{ insert: ' the ' },
{ insert: 'Grey', attributes: { color: '#cccccc' } }
]
}
insert:插入内容 attributes:格式属性
记录光标代码片段:
let quill = this.$refs.myQuillEditor.quill
let length = quill.selection.savedRange.index
this.currentPoint = length
在记录的光标位置插入:
this.selectParams = '${' + citem + '}'
this.$refs.myQuillEditor.quill.insertText(this.currentPoint, this.selectParams, true)
this.currentPoint += this.selectParams.length
将delta数据渲染到富文本:
this.$refs.myQuillEditor.quill.setContents(delta)