vue2项目中需要使用 quill 实现富文本展示、编辑以及插入图片的功能。
quill 官网:https://quilljs.com/docs/api/#insertembed
但原始功能流程是点击插入图片会直接出现文档弹窗,而我需要实现的功能是点击插入图片调出自定义弹窗如下:
实现步骤如下:
1、安装:npm install quill --save
2、页面引入:import Quill from 'quill';
3、页面使用:
<template>
<div id="editorQuill"></div>
<!-- 插图弹窗 -->
<el-dialog
title="内容插图"
:visible.sync="insertDialog"
width="85%">
// 内容自定义,此处省略
</el-dialog>
</template>
<script>
import Quill from 'quill';
export default {
data() {
return {
quill:null, // 富文本
insertDialog:false, //弹窗
selectionIndex:0, //插入位置
}
},
mounted() {
// 生成富文本组件,传入dom的ID,和配置
this.quill = new Quill('#editorQuill', {
modules: {
toolbar: ['image']
},
theme: 'snow'
});
// 获取工具栏模块,然后添加图片工具的处理函数
const toolbar = this.quill.getModule('toolbar');
toolbar.addHandler('image', this.customImageHandler);
},
methods: {
// 自定义插入图片的处理函数
customImageHandler(){
// 存储当下的光标位置
this.selectionIndex = this.quill.getSelection().index || 0
// 显示弹窗(可替换为其他自定义内容)
this.insertDialog = true
},
},
}
</script>
<style lang="scss" scoped>
#editorQuill{
width: 100%;
height: 450px;
}
</style>
这里要补充的是,如果富文本框需要展示接口数据,用以下方式进行赋值:
// 调取接口举例,请按照具体项目封装方式进行
getInfo(){
info().then(res => {
if(res.code == 200){
//接口返回的数据赋值,重点
this.quill.root.innerHTML = res.data.content
}
})
},
当选择图片后,获取图片url,使用以下方式进行插入:
// 添加图片进富文本,第一个参数是光标位置,第二个是添加的类型,第三个是图片(最好是url)
this.quill.insertEmbed(this.selectionIndex, 'image', url);
该功能可根据具体需求自定义处理函数,欢迎大家提出问题一同交流!