实现效果
文本编辑的三个功能分别是:添加链接,上传图片,上传文件
编辑器配置
基本配置
<template>
<quill-editor class="editor" ref="QuillEditor" v-model="detail" :options="editorOption"></quill-editor>
</template>
<script>
// 编辑器工具栏配置
const toolbarOptions = [
['link', 'image', 'upload']
]
export default {
data() {
detail: '',
editorOption: {
modules: {
toolbar: {
container: toolbarOptions, // 工具栏
handlers: {
image: function(value) { //编辑器-上传图片
if (value) {
// 调用antd图片上传upload
document.querySelector('.uploadImg .ant-upload .ant-btn').click()
} else {
this.quill.format('image', false)
}
},
upload: value => { //编辑器-上传文件
if (value) {
document.querySelector('.uploadFile input').click()
}
}
}
}
}
}
}
}
</script>
实现图片上传
想法:隐藏upload组件,当用户点击上传图片的icon时,触发upload的点击,调用上传图片接口,服务器返回图片地址后,添加到光标停留的地方
<!--携带了头部header参数token-->
<a-upload
name="img"
:multiple="true"
:showUploadList="false"
:action="front"
:headers="{Authorization: 'bearer ' + userInfo.token}"
class="uploadImg"
style="display: none"
@change="uploadImg"
>
<a-button>上传图片</a-button>
</a-upload>
// 编辑器 - 上传图片
uploadImg(info) {
let quill = this.$refs.QuillEditor.quill
if (info.file.status === 'uploading') {
return
}
if (info.file.status === 'done') {
if (info.file.response.errno === 0) {
// 获取光标所在位置
let length = quill.getSelection().index
// 插入图片,res为服务器返回的图片链接地址
quill.insertEmbed(length, 'image', info.file.response.data)
// 调整光标到最后
quill.setSelection(length + 1)
}
}
}
实现文件上传
想法:同理,隐藏upload组件,当用户点击上传文件的icon时,触发upload的点击,调用上传文件接口,服务器返回文件地址后,添加到光标停留的地方;不过,这里要自定义一个文件的icon
import { Quill } from 'vue-quill-editor'
// 自定义插入a链接
var Link = Quill.import('formats/link')
class FileBlot extends Link {
// 继承Link Blot
static create(value) {
let node = undefined
if (value && !value.href) {
// 适应原本的Link Blot
node = super.create(value)
} else {
// 自定义Link Blot
node = super.create(value.href)
// node.setAttribute('download', value.innerText); // 左键点击即下载
node.innerText = value.innerText
node.download = value.innerText
}
return node
}
}
FileBlot.blotName = 'link'
FileBlot.tagName = 'A'
Quill.register(FileBlot)
注意这里 - 插入文件地址的方式
// 编辑器 - 上传文件
uploadFile(info) {
let quill = this.$refs.QuillEditor.quill
if (info.file.status === 'uploading') {
return
}
if (info.file.status === 'done') {
if (info.file.response.errno === 0) {
// 获取光标所在位置
let length = quill.getSelection().index
// 插入文件,res为服务器返回的文件链接地址
quill.insertEmbed(length, 'link', {href: info.file.response.data, innerText: info.file.name}) //**注意这里 - 插入文件地址的方式**
// 调整光标到最后
quill.setSelection(length + 1)
}
}
}
最后的效果图:
点击文件链接,直接下载这个文件