前言
- 前言
上文介绍了quill的基础使用,这里主要针对我们不想以图片base64文本格式提交,而是上传服务器获取图片url,以url提交的实现方式以及视频上传的实现
- 思路
1、隐藏一个input框,使用quill的handler事件实现点击上传到服务器
这种方式可以参考作者再见紫罗兰https://www.cnblogs.com/linxiyue/p/10305047.html
2、由于项目使用饿了么,所以我直接使用其提供的upload组件和Quill自定义定制组合实现上传图片和视频的功能
两个思路方法一直,都可以实现
上传图片
import Quill from "quill";
import {
quillRedefine} from 'vue-quill-editor-upload'
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
components:{
quillRedefine },
options: {
theme: "snow",
bounds: document.body,
debug: "warn",
modules: {
// 工具栏配置
toolbar: {
container:[
["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
["blockquote", "code-block"], // 引用 代码块
[{
list: "ordered" }, {
list: "bullet" }], // 有序、无序列表
[{
indent: "-1" }, {
indent: "+1" }], // 缩进
[{
size: ["small", false, "large", "huge"] }], // 字体大小
[{
header: [1, 2, 3, 4, 5, 6, false] }], // 标题
[{
color: [] }, {
background: [] }], // 字体颜色、字体背景颜色
[{
align: [] }], // 对齐方式
["clean"], // 清除文本格式
["link", "image", "video"], // 链接、图片、视频
]
},
},
placeholder: "请输入内容",
readOnly: false,
lenIndex: 0 // 索引
},
//auth.js
export function getToken() {
return Cookies.get(TokenKey)
}
1、引入token
import { getToken } from "@/utils/auth";
2、上传参数
upload: {
// 设置上传的请求头部
headers: { Authorization: "Bearer " + getToken() },
// 上传的地址
url: process.env.VUE_APP_BASE_API + "/file?type=1"
},
<div
class="editor"
ref="editor"
@focus="onEditorFocus($event)"
@change="onEditorChange($event)"
:style="styles">
</div>
<el-upload
class="uploadder-ed"
name="file"
:headers="upload.headers"
:action="upload.url"
:show-file-list="false"
:on-success="handleFileSuccess"
>
</el-upload>
解释:
@focus="onEditorFocus($event)" 获取焦点事件
@change="onEditorChange($event)"// 内容改变事件
:on-success="handleFileSuccess"// 文件上传成功执行函数
// 获得焦点事件
onEditorFocus(e){
this.lenIndex = e.getSelection().index; },
// 内容改变事件
onEditorChange(e){
this.lenIndex = e.quill.getSelection().index; },
// 文件上传成功处理
// option下添加handlers
handlers: {
'image': function (value) {
if (value) {
// 触发input框选择图片文件
document.querySelector('.uploadder-ed input').click()
} else {
this.quill.format('image', false);
}
},
}
- el-upload执行handleFileSuccess将地址插入到编辑器中:
// methods下封装上传函数
handleFileSuccess(response, file, fileList) {
if (response.code == 200) {
this.Quill.insertEmbed(this.lenIndex, 'image', response.data.url); // 创建img标签
this.Quill.setSelection(this.lenIndex + 1)
}
},
上传视频
同样步骤
upload组件
<el-upload
class="upload-demo"
name="file"
:headers="upload.headers"
:action="upload.url"
:show-file-list="false"
:on-success="handleFileSuccess1"
>
</el-upload>
option下handlers里面添加
'video': function (value) {
if (value) {
// 触发input框选择图片文件
document.querySelector('.upload-demo input').cl