quill富文本编辑器,如何在文本框插入自定义元素

1,194 阅读2分钟

quill简介

quill是一个开源轻量级的富文本编辑器,下载量相比较其他编辑器目前最高,基本能满足开发需求。 quill支持自定义blot,简单理解就是可以自定义对选中的文本做样式、或在文本里插入新元素。

quill中默认定义的blot常见的包括TextBlot(行内普通文本)、Inline(行内携带样式的普通文本)、Block(块级行,一般以段落p为单位)、Break(换行)、Image(图片IMG插入)、Bold(加粗文本)。

开发需求

实现在文本编辑框中任意文本中插入选择框,选择内容后,生成新的文本。

实现思路

要实现插入选择框,即是在文本编辑框中插入一个自定义的行内元素

1. 安装quill

npm install --save quill

2. main文件引入css

//引入quill的两种主题风格之一:snow简约风格 另一种bubble可以试用一下,下面代码中详见如何使用
import 'quill/dist/quill.snow.css'

3. 新建blot自定义文件

import Quill from 'quill'
//const BlockEmbed = Quill.import('blots/block/embed') //插入块级元素
const Embed = Quill.import('blots/embed') //插入行内元素span 这里是span包裹select的格式
class SelectBlot extends Embed {
   static create (value) {
      //value是传入的初始值
      const node = super.create()
      node.setAttribute('data-value',value)
      //创建select元素
      const select = document.createElement('select')
      const opt = document.createElement('option')
      opt.value = ''
      opt.disabled = true
      opt.selected = true
      opt.label = '请选择'
      select.appendChild(opt)
      
      //options 选框列表
      options.forEach((option)=>{
        const opt = document.createElement('option')
        opt.value = option.value
        opt.label = option.label
        select.appendChild(opt)
      })
      select.value = value
      select.addEventListener('change',()=>{
        const selectedVal=select.value
        node.setAttribute('data-value',selectedVal)
      })
      node.appendChild(select)
      return node 
   }
   static formats(node){
     return node.getAttribute('data-value')
   }
}
SelectBlot.blotName = 'mySelect' //自定义blot名称
SelectBlot.tagName = 'span'  //元素标签
//注册blot并抛出
Quill.register(SelectBlot)
export { Quill }

4. 引入使用

//html
<div ref='editor' class='w-full'></div>
<button @click='clickHandler'>插入选择框<button>
//js
import {Quill} from '创建的blot文件路径'
const editor = ref()
const global = { quill: null }
//
onMounted(
  if(editor.value){
    const quill = new Quill(editor.value, {
      modules:{
       toolbar:false  //工具栏,这里可以设置需要的工具,例如['bold','italic','underline','strike']
      },
      theme:'snow' //主题
    })
    global.quill = quill
  }
)

const clickHandler=()=>{
 const quillInstance = global.quill
 const range = quillInstance.getSelection()
 if(range){
   quillInstance.insertEmbed(range.index,'mySelect','')  //参数(哪个位置,blot名称,初始值)
 }
}

const fullContents=ref(''//文本框内容处理
const confirmHandler=()=>{
  const contents=global.quill.getContents()  //获取文本框内容
  fullContents.value=''
  //contens.ops获取的是delta格式的,需要处理拼接
  contents.ops.forEach((op)=>{
    if(op.insert){
      //原文本
      if(typeof op.insert==='string'){
        fullContents.value+= op.insert
      //插入的选择框文本内容
      }else if(op.insert.mySelect){
         if(op.attributes){
            const str= Object.values(op.attributes).join('')
            fullContents.value+=str
         }
      }
    }
  })
}


最后,贴一个quill官网文档参考

Quickstart - Quill Rich Text Editor (quilljs.com)