基于vue-quill-editor二次封装,可以实现自定义文件上传

实现步骤

  1. 先将vue-quill-editor组件引入进来,自定义配置,在自定义配置中添加upload操作,但是由于vue-quill-editor组件不支持文件上传,该操作是无效的,逻辑需要自己去实现
  2. 给添加的upload按钮自定义css样式,文件上传的图标,大小等
  3. 模拟upload点击事件,在editor的配置中,有一个handler对象,来处理自定义的upload点击
  4. 点击之后我们去让他触发element-ui中的文件上传组件的上传操作,所以我们将el-upload组件放在页面上,然后用css隐藏起来,在点击富文本中upload图标时,来模拟点击el-upload,弹出上传文件操作框
  5. 然后自定义el-upload的上传方法,在上传后的回调中去调用自己的接口,拿到一个文件路径字符串
  6. 再将这个字符串通过quill对象插入到富文本中,也就是vue-quill-editor组件依赖的父对象,掺入a链接是通过继承父类中的create方法来实现
  7. 其他不明白的可以看代码中的注释

完整代码

1、quill-editor-upload自定义组件

<template>
  <div>
    <quill-editor ref="quillEditor" :options="editorOption" :content="content" @change="onEditorChange($event)"
      @blur="$emit('blur')"></quill-editor>
    <!-- 隐藏的upload -->
    <el-upload class="uploadFile" drag action="#" :http-request="uploadFile" :limit="1" :on-exceed="handleExceed"
      :on-remove="handleRemove" :file-list="fileList">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处,或<em>点击上传</em>
      </div>
    </el-upload>
  </div>
</template>

<script>
import Quill from 'quill';
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { editorUploadPath } from "@/api/excel/excel.js";

// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],

  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
  [{ 'list': 'ordered' }, { 'list': 'bullet' }],
  [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
  [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
  [{ 'direction': 'rtl' }],                         // text direction

  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
  [{ 'font': [] }],
  [{ 'align': [] }],
  ['link', 'image', 'video', 'upload'],
  ['clean']                                         // remove formatting button
]

// 自定义插入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);

export default {
  name: "quill-editor-upload",
  components: { quillEditor },
  // 自定义v-model,prop为props中的属性,代表v-model传入的值;event表示反向输出给v-model的事件名
  model: {
    prop: 'content',
    event: 'changeContent'
  },
  // 自定义v-model, v-model传入的值
  props: {
    content: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileList: [], // 文件列表
      // editor配置
      editorOption: {
        placeholder: '请输入正文......',
        modules: {
          toolbar: {
            container: toolbarOptions,  // 工具栏
            handlers: {
              // 模拟upload按钮点击事件
              'upload': (value => {
                if (value) {
                  document.querySelector('.uploadFile input').click()
                }
              })
            }
          }
        }
      }
    }
  },
  methods: {
    // 自定义v-model,将editor选择器change事件提供的html传出去
    onEditorChange(e) {
      this.$emit('changeContent', e.html)
    },
    // 自定义文件上传
    uploadFile(res) {
      // console.log('上传成功', res);
      let myFormData = new FormData();
      myFormData.append("file", res.file);
      editorUploadPath(myFormData).then((response) => {
        if (response.code === 0) {
          let fileNameLength = res.file.name.length
          // 插入链接
          let quill = this.$refs.quillEditor.quill
          let length = quill.getSelection().index;
          quill.insertEmbed(length, 'link', { href: response.msg, innerText: res.file.name }, "api")
          quill.setSelection(length + fileNameLength)
          this.fileList = []
        }
      });
    },
    // 文件超出限制提示
    handleExceed() {
      this.$message.warning(`当前限制选择 1 个文件,请删除后更新!`);
    },
    // 移除文件
    handleRemove() {
      this.fileList = [];
    },
  }
}
</script>

<style scoped>
/* 文件上传图标样式 */
/deep/ .quill-editor .ql-snow.ql-toolbar .ql-formats .ql-upload {
  background: url("../assets/file.png");
  background-size: 16px 16px;
  background-position: center center;
  background-repeat: no-repeat;
}

/* 隐藏upload上传,用模拟事件触发 */
.uploadFile {
  width: 0;
  height: 0;
  display: none;
}
</style>

2、使用该组件

<el-form-item label="内容" prop="content">
    <quillEditorUpload v-model="form.content"></quillEditorUpload>
</el-form-item>
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值