当前位置: 代码网 > it编程>前端脚本>Vue.js > vue使用quill编辑器自定义图片上传方法、quill-image-resize-module修改图片、监测粘贴的是图片上传到后端、重新进入编辑器img标签丢失style属性

vue使用quill编辑器自定义图片上传方法、quill-image-resize-module修改图片、监测粘贴的是图片上传到后端、重新进入编辑器img标签丢失style属性

2024年08月03日 Vue.js 我要评论
vue使用quill编辑器自定义图片上传方法、quill-image-resize-module修改图片大小样式、监测粘贴的是图片上传到后端、重新进入编辑器img标签丢失style样式属性,img样式丢失

1、自定义图片上传

需求:

  • 因为在展示页面使用到了vue-photo-preview组件实现点击图片预览,所以需要修改image.ts进行修改添加预览组件需要的previewpreview-text属性,效果图如下:
    上传图片添加属性
  • 展示页面点击图片预览:
    在这里插入图片描述实现方法:
  1. 到quill到github:https://github.com/quilljs/quill/tree/develop复制image.ts到自己新建的image.js进行改写create,image.ts路径:packages/quill/src/formats/image.ts
    image.js修改处
    	  static create(value) {
    	    const node = super.create(value);
    	    if (typeof value === "string") {
    	      // 保留原来的图片方法
    	      node.setattribute("src", this.sanitize(value));
    	    } else {
    	      // 自定义图片方法
    	      node.setattribute("src", value.src);
    	      // 使用了vue-photo-preview,所以添加preview,preview-text这两个属性
    	      node.setattribute("preview", "1"); //preview相同的为一组,这里所有上传图片为一组
    	      node.setattribute("preview-text", value.title); //图片名称,预览时显示使用
    	    }
    	    return node;
    	  }
    	```
    
  • image.js完整代码:
    import quill from "quill";
    let embedblot = quill.import("formats/image");
    //添加style,解决重进编辑器ima标签丢掉style属性问题
    const attributes = ["alt", "height", "width", "style"];
    
    class image extends embedblot {
      static blotname = "image";
      static tagname = "img";
    
      static create(value) {
        const node = super.create(value);
        if (typeof value === "string") {
          // 保留原来的图片方法
          node.setattribute("src", this.sanitize(value));
        } else {
          // 自定义图片方法
          node.setattribute("src", value.src);
          // 使用了vue-photo-preview所以添加preview,preview-text这两个属性
          node.setattribute("preview", "1"); //preview相同的为一组
          node.setattribute("preview-text", value.title); //图片名称,预览时显示使用
        }
        return node;
      }
    
      static formats(domnode) {
        return attributes.reduce((formats, attribute) => {
          if (domnode.hasattribute(attribute)) {
            formats[attribute] = domnode.getattribute(attribute);
          }
          return formats;
        }, {});
      }
    
      static match(url) {
        return /\.(jpe?g|gif|png)$/.test(url) || /^data:image\/.+;base64/.test(url);
      }
    
      static register() {
        if (/firefox/i.test(navigator.useragent)) {
          settimeout(() => {
            // disable image resizing in firefox
            // @ts-expect-error
            document.execcommand("enableobjectresizing", false, false);
          }, 1);
        }
      }
    
      static sanitize(url) {
        return sanitize(url, ["http", "https", "data"]) ? url : "//:0";
      }
    
      static value(domnode) {
        return domnode.getattribute("src");
      }
    
      format(name, value) {
        if (attributes.indexof(name) > -1) {
          if (value) {
            this.domnode.setattribute(name, value);
          } else {
            this.domnode.removeattribute(name);
          }
        } else {
          super.format(name, value);
        }
      }
    }
    function sanitize(url, protocols) {
      const anchor = document.createelement("a");
      anchor.href = url;
      const protocol = anchor.href.slice(0, anchor.href.indexof(":"));
      return protocols.indexof(protocol) > -1;
    }
    
    export default image;
    
    
  1. vue页面引入image.js
    import quill from "quill";
    import image from "./image";
    quill.register(image, true);
    
  2. 修改el-upload组件上传成功后回调函数中的quill.insertembed()传参,
        handleuploadsuccess(res, file) {
      // 获取富文本组件实例
      let quill = this.quill;
      // 如果上传成功
      if (res.code === 200) {
        let shiftlength = 1;
        if (this.uploadtype == "image") {
          // 插入图片  res.url为服务器返回的图片地址
          quill.insertembed(this.lastselection, "image", {
            src: process.env.vue_app_base_api + res.data.fileaddress, //上传图片后端返回地址
            title: res.data.originalname, //上传图片名称
          });
        } 
        // 调整光标到最后
        quill.setselection(this.lastselection + shiftlength);
        this.$modal.closeloading();
      } else {
        this.$modal.closeloading();
        this.$modal.msgerror("上传失败,请重试");
      }
    },
    

2、使用quill-image-resize-module插件修改上传的图片尺寸,对齐方式

1. 安装
npm install quill-image-resize-module -- save
2. 引用报错问题解决
  • 报错cannot read properties of undefined (reading 'impoerts')
    在这里插入图片描述
  • 解决办法:修改vue.config.js,添加配置
    // 20230801添加ts配置
    configurewebpack: {
    // 添加配置解决vue 引入quill - image - resize - module 插件报错
    	plugins: [
          new webpack.provideplugin({
            "window.quill": "quill/dist/quill.js",
            quill: "quill/dist/quill.js",
          }),
      ],
    },
    
  • 报错quill cannot import modules/imageresize. are you sure it was registered?
    在这里插入图片描述
  • 解决方法:不要在组件内引入插件注册,在main.js内引入并且注册
    javascript // 富文本上传图片调整大小 import quill from "quill"; import imageresize from "quill-image-resize-module"; // 调整大小组件。 window.quill = quill; quill.register("modules/imageresize", imageresize);
3. 在vue页面添加quill配置项imageresize
	 options: {
        theme: "snow",
        bounds: document.body,
        debug: "warn",
        modules: {
          // 工具栏配置
          toolbar: {
          container: [],
          handlers: {},
          imageresize: {
            //放大缩小
            displaystyles: {
              backgroundcolor: "black",
              border: "none",
              color: "white",
            },
            modules: ["resize", "displaysize", "toolbar"],
            // resize: 允许缩放、displaysize:缩放是显示像素、toolbar:显示工具栏,用于设置图片居中等样式
          },
          // imagedrop: true, //图片拖拽
        },
        placeholder: "请输入内容",
        readonly: this.readonly,
      },

3、重新进入编辑器img标签丢失style属性

  • 在修改的image.js添加‘style’属性即可
    //添加style,解决重进编辑器ima标签丢掉style属性问题
    const attributes = ["alt", "height", "width", "style"];
    

4、监测粘贴的是图片上传到后端

  • 初始化quill编辑器时,添加监听粘贴事件
	// 添加监听事件
	editor.addeventlistener("paste", this.handlepaste, true);
    /** 监听粘贴 -如果是图片则将图片上传到服务器*/
    handlepaste(evt) {
      if (
        evt.clipboarddata &&
        evt.clipboarddata.files &&
        evt.clipboarddata.files.length
      ) {
        evt.preventdefault();
        [].foreach.call(evt.clipboarddata.files, (file) => {
          // 判断粘贴的是否是图片,不是图片则return
          if (!file.type.match(/^image\/*/i)) {
            return;
          }
          const formdata = new formdata();
          formdata.append("file", file); //后台上传接口的参数名
          // 获取光标所在位置
          let quill = this.quill;
          if (!(quill.selection && quill.selection.savedrange)) {
            this.$modal.msgerror("上传失败,请重试");
            return;
          }
          this.lastselection = quill.selection.savedrange.index;
          this.$modal.loading("正在上传文件,请稍候...");
          this.uploadtype = "image";
          // 实现上传
          upload(formdata)
            .then((res) => {
              // 调用上传成功回调函数
              this.handleuploadsuccess(res);
            })
            .catch((error) => {
              //上传失败回调
              this.handleuploaderror();
            });
        });
      }
    },
(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com