使用百度UEditor

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24147051/article/details/84533239

百度UEditor展示

在这里插入图片描述
如上图所示,是一个百度UEditor富文本编辑器。这里就讲解一下:如何使用百度UEditor,添加toolbar以及如何实现上传本地图片,和将外部黏贴进来的图片进行地址替换。


使用百度UEditor前遇到的问题

大家知道,富文本编辑器有很多种。我一个星期前用了Vue2Editor发现,这个的封装存在很多问题。它是使用了quill的这个库,但是呢,利用的还是有很多问题。比如:toolbar无法进行自定义外部复制来东西会格式化样式
在这里插入图片描述
在这里插入图片描述


使用百度UEditor

在这里插入图片描述

(1) 引入+ 组建内注册:
import VueUeditorWrap from "vue-ueditor-wrap";
export default {
  components: {
    VueUeditorWrap,   
  },
  data(){
	  return{
	  	data.pageContent = "";
	  	editorConfig: {
		        // 如果需要上传功能,找后端小伙伴要服务器接口地址
		        serverUrl: "/book/update/upload",
		        // 你的UEditor资源存放的路径,相对于打包后的index.html(路由使用history模式注意使用绝对路径或者填写正确的相对路径)
		        UEDITOR_HOME_URL: "/static/UEditor/",
		        // 编辑器不自动被内容撑高
		        autoHeightEnabled: false,
		        // 初始容器高度
		        initialFrameHeight: 600,
		        // 初始容器宽度
		        initialFrameWidth: "100%",
		        // 关闭自动保存
		        enableAutoSave: false
		      },
     	editorInstance: null,
	  }
  }
}
(2) 在view中进行展示:
 <vue-ueditor-wrap
                    ref="ueditor"
                    v-model="data.pageContent"
                    :config="editorConfig"
                    :destroy="true"
                    :init="initUeditor"
                    @ready="ueditorReady"
                  />
(3) methods:里面的方法 (批量上传外部图片)

在这里插入图片描述

    ueditorReady(editorInstance) {
      this.editorInstance = editorInstance;
    },
    initUeditor() {
      // 注册富文本框按钮(这里讲解:第一张图中最后两个图片按钮:单张上传和批量上传的操作)
      const _this = this;
      window.UE.registerUI("上传外部图片", (editor, uiName) => {       /*----------上传外部图片按钮-----------*/
        // 注册按钮执行时的command命令,使用命令默认就会带有回退操作
        editor.registerCommand(uiName, {
          execCommand() {
            const doc = new DOMParser().parseFromString(
              _this.editorInstance.getContent(),
              "text/html"
            );
            const imgs = doc.querySelectorAll("img");
            if (!imgs.length) return;
            editor.setDisabled();

            _this.uploadImg(imgs, doc, editor);
          }
        });

        // 创建一个button
        const btn = new window.UE.ui.Button({
          // 按钮的名字
          name: uiName,
          // 提示
          title: uiName,
          // 需要添加的额外样式,指定icon图标,这里默认使用一个重复的icon
          cssRules: "background-position: -726px -76px;",
          // 点击时执行的命令
          onclick() {
            // 这里可以不用执行命令,做你自己的操作也可
            editor.execCommand(uiName);
          }
        });
        return btn;
      });

      window.UE.registerUI(                  /*----------上传内部图片按钮-----------*/
        "上传图片",
        (editor, uiName) => {
          editor.registerCommand(uiName, {
            execCommand() {
              _this.$refs.fileInputHidden.click();
            }
          });
          const btn = new window.UE.ui.Button({
            name: uiName,
            title: uiName,
            cssRules: "background-position: -380px 0px;",
            onclick() {
              editor.execCommand(uiName);
            }
          });
          return btn;
        },
        44
      );
    },
    // 获取图片地址
    uploadImg(imgs, doc, editor) {
      if (imgs) {
        if (imgs.length === 0) {
          this.$message({
            type: "warning",
            message: "请先放置图片!"
          });
        }
        this.uploadSingle(imgs, 0, doc, editor);
      }
    },
   // 批量上传外部图片
    uploadSingle(imgs, i, doc, editor) {
      if (imgs.length === i) {
        this.enableEditor(doc, editor);
        return;
      }
      const img = imgs[i];
      if (img.src.indexOf("你不想转换的图片地址片段") >= 0) {  
        this.uploadSingle(imgs, (i += 1), doc, editor);
        return;
      }
      DataResearch.getImageDataUrl({ url: img.src })   //  调用更改图片地址接口(你们公司的更改图片地址接口)
        .then(
          res => {
            this.imageChange(res, resolve => {    // 获得更改后的图片地址
              img.setAttribute("src", resolve);
              this.uploadSingle(imgs, (i += 1), doc, editor);   // 进行递归的上传图片
            });
          },
          resolve => {
            throw resolve;
          }
        )
        .then(() => {
          this.$message({
            type: "success",
            message: "图片上传成功!"
          });
        });
    },
       // 将传外部图片地址修改为你们公司的地址
    imageChange(file, getdata) {
      const uploadData = getFormData({
        file,
        a_id: this.admin.admin_id,
        a_token: this.admin.app_token,
        prefix: "shop-manage/product",
        overwrite: 2
      });
      const imageTypes = ["image/jpeg", "image/png", "image/gif"];
      const validType = imageTypes.some(
        type => type === String(file.type).toLowerCase()
      );
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!validType) {
        this.$message.error("上传图片格式错误!");
        return false;
      }
      if (!isLt5M) {
        this.$message.error("上传图片大小不能超过 5MB!");
        return false;
      }
      axios({
        method: "post",
        url: `${this.config.fs_url}/upload`,  // 你们公司的修改图片地址接口
        data: uploadData
      })
        .then(res => getdata(res.data.data.url))
        .catch(() => {
          this.$message.error("图片上传失败,请稍后重试");
        });
    },
(4) methods:里面的方法 (单张上传内部图片)

在这里插入图片描述
原理:

  1. 写一个input输入框并将其type设置为文件类型,将其隐藏。
  2. 当点击上传内部图片按钮时,去调用该input框的change方法

view里面

<input
                    ref="fileInputHidden"
                    type="file"
                    style="display: none"
                    @change="uploadHiddenFile">

methods:里面的方法

    uploadHiddenFile() {
      const file = this.$refs.fileInputHidden.files[0];
      this.imageChange(file, url => {
        this.editorInstance.focus();
        this.editorInstance.execCommand("inserthtml", `<img src=${url}>`);
      });
    },
    // 将传外部图片地址修改为哒哒地址
    imageChange(file, getdata) {
      const uploadData = getFormData({
        file,
        a_id: this.admin.admin_id,
        a_token: this.admin.app_token,
        prefix: "shop-manage/product",
        overwrite: 2
      });
      const imageTypes = ["image/jpeg", "image/png", "image/gif"];
      const validType = imageTypes.some(
        type => type === String(file.type).toLowerCase()
      );
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!validType) {
        this.$message.error("上传图片格式错误!");
        return false;
      }
      if (!isLt5M) {
        this.$message.error("上传图片大小不能超过 5MB!");
        return false;
      }
      axios({
        method: "post",
        url: `${this.config.fs_url}/upload`,
        data: uploadData
      })
        .then(res => getdata(res.data.data.url))
        .catch(() => {
          this.$message.error("图片上传失败,请稍后重试");
        });
    },

猜你喜欢

转载自blog.csdn.net/qq_24147051/article/details/84533239
今日推荐