quill富文本编辑器----图片、视频处理

前端在开发时,可能会使用到富文本编辑器,作为vue项目中,quill是一款不错的富文本编辑器,但是,它有一个问题,即如果在富文本中添加图片或视频时,会将本地的媒体文件转为base64,如果我们不处理这些问题时,会使得到的输入内容过长,一方面网络加载很慢,另一方面可能会导致后台在创建数据库进,内容溢出,所以,无论对前端还是后台而言,都需要将被保存的文件单独上传,将img标签中src的值替换为上传后的地址。

下面我们将从头开始,实现这个功能,当然,前提我们需要有一个vue前端项目,可以直接使用vue-cli来创建,也可以直接下载一些搭建好的空白项目,此处略去方法或步骤。

1. 首先:我们在项目中引入quill

npm install -S quill

2. 在使用的地方引入quill 根据实际情况引入quill组件及其样式,可以全局引入,也可以在单个页面中引入。

// 1. 全局引入,在main.js中引入
import Quill from "quill"
Vue.use(Quill)
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css";

// 2. 局部引入,一般会把它封装为一个组件,方便多次使用
// 在components/QuillEditor/index.vue中引入quill
import Quill from "quill";
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css";

3. 初始化编辑器,配置编辑器

  1. 在template创建一个富文本的载体div,再创建一个隐藏的input,用于图片上传,设置好accept
<div>
 <div id="editor" class="eidtor" ref="editor"> </div>
 <input type="file" @change="picChange" style="display: none;" id="picInput">
</div>
  1. 初始化富文本编辑器
import Quill from "quill"
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css";
export default {
 data() {
  return {
   quill: null
  }
 },
 mounted() {
  // 注意,不要在created中初始化,可能会导致找不到div
   this.initEDditor();
 },
 methods: {
  // 配置方法,可以直接写在data中
  getOptions() {
    return {
    theme: "snow",
    debug: "warn",
    modules: [
      toolbar: [
          ["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"]                       // 链接、图片、视频
        ]
      ]
    }
  },
  initEditor() {
      let options = this.getOptions();
      this.quill = new Quill("#editor", options);
  },
 }
}
  1. 添加图片上传,并将上传后得一的url放回到编辑器中对应的img标签中,当然,在此之前需要下载发送请求的工具,如我们常用的axios。
npm install -S axios

此时的原理是:当我们监听到点击上传图片时,将我们隐藏的input被点击,此时,会调起选择文件的框,当我们选中了文件后,直接使用input的change事件,使用我们写好的上传图片的方法,当图片上传成功后,我们调用quill为我们提供的insertEmbed方法,将图片上的路径存放到这个富文本中,当我们了了解了这个原理后,可以实现视频上传了(关于视频上传的代码就不贴出来了)。具体代码如下:

  mounted() {
    this.initEDditor();
    this.quill.getModule("toolbar").addHandler("image", this.uploadImg)
  },
  methods: {
    uploadImg(e) {
      document.getElementId("picInput").click();
    },
    //  选择完图片后
    picChange(e) {
      let file = e.target.files[0];
      let fm = new FormData();
      fm.append("file", file);
      this.postImg(fm).then(res =>{
        // 下面的方法是我从网上查找的资料,也可能是官方提供 的方法,不过可以实现
        let addImageRange = this.quill.getSelection();
        let newRange = 0 + (addImageRange !== null ? addImageRange.index : 0);
        //  res.url为上传成功后由后台返回的图片访问路径
       this.quill.insertEmbed(newRange, "image", res.url);
       this.quill.setSelection(1 + newRange);
      })
    },
    //  图片上传接口
    postImg(fm) {
      let token = getToken();  // 获取token,根据实际来实现
      let headers = {
        "Content-Type": "multipart/form-data",
        Authorization: "Bearer " + token
      }
      return new Promise(resolve =>{
        axios({
          url: "xxx",
          method: "post",
          data: fm,
          headers: headers
        })
      }).then(res =>{
        if (res.data.code == 200) {
           resolve(res.data);
        } else {
          this.$message.error(res.data.msg)
        }
      }).catch(err =>{
        this.$message.error(err.msg || "服务器错误,请稍候再试");
      })
    }
}
  1. 既然做为一个组件,得需要回显数据、向父组件传值等操作,所以,我们还需要添加上quill为我们提供好的回调方法和向编辑器传值的方法
      initEditor() {
        let options = this.getEditorOptions();
        this.quill = new Quill("#editor", options);

        this.quill.pasteHTML(this.currentValue);
        this.quill.on("text-change", (delta, oldDelta, source) => {
            const html = this.$refs.editor.children[0].innerHTML;
            const text = this.quill.getText();
            const quill = this.quill;
            this.currentValue = html;
            this.$emit("input", html);
            this.$emit("on-change", { html, text, quill });
        });
        this.quill.on("text-change", (delta, oldDelta, source) => {
            this.$emit("on-text-change", delta, oldDelta, source);
        });
        this.quill.on("selection-change", (range, oldRange, source) => {
            this.$emit("on-selection-change", range, oldRange, source);
        });
        this.quill.on("editor-change", (eventName, ...args) => {
            this.$emit("on-editor-change", eventName, ...args);
        });
    },
		
//   添加watch监听,防止因渲染的生命周期方法导致页面无法回显数据
	 watch: {
    value: {
      handler(val) {
        if (val !== this.currentValue) {
          this.currentValue = val === null ? "" : val;
          if (this.quill) {
            this.quill.pasteHTML(this.currentValue);
          }
        }
      }
    },
  },

如些,我们的editor也算是封装完成 了,当然 还需要加上上结class样式,下面是完整的代码

<template>
  <div>
      <div id="editor" class="eidtor" ref="editor"></div>
      <input type="file" id="picInput" style="display: none;" @change="picChange">
  </div>
</template>

<script>
import Quill from "quill"
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css";
import axios from 'axios';
export default {
  data() {
    return {
      quill: null,
      currentValue: ""
    }
  },
  props: {
    /* 编辑器的内容 */
    value: {
      type: String,
      default: "",
    },
  },
  mounted() {
      this.initEditor();
      this.quill.getModule("toolbar").addHandler("image", this.uploadImage);
  },
  watch: {
    value: {
      handler(val) {
        if (val !== this.currentValue) {
          this.currentValue = val === null ? "" : val;
          if (this.Quill) {
            this.Quill.pasteHTML(this.currentValue);
          }
        }
      }
    },
  },
  methods: {
    //   quill的配置内容
    getEditorOptions() {
        let options = {
            debug: "warn",
            modules: {  // 配置工具栏
                toolbar: [
                    ["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"]                       // 链接、图片、视频
                ]
            },
            placeholder: "请输入文本内容",
            readOnly: false,
            theme: "snow"  //  官方给定的theme有两种,一种为snow:标准工具栏主题;bublle:浮动提示主题
        }
        return options;
    },

    // 初始化quill对象
    initEditor() {
        let options = this.getEditorOptions();
        this.quill = new Quill("#editor", options);

        this.quill.pasteHTML(this.currentValue);
		// 下面的方法按需调用
        this.quill.on("text-change", (delta, oldDelta, source) => {
            const html = this.$refs.editor.children[0].innerHTML;
            const text = this.quill.getText();
            const quill = this.quill;
            this.currentValue = html;
            this.$emit("input", html);
            this.$emit("on-change", { html, text, quill });
        });
        this.quill.on("text-change", (delta, oldDelta, source) => {
            this.$emit("on-text-change", delta, oldDelta, source);
        });
        this.quill.on("selection-change", (range, oldRange, source) => {
            this.$emit("on-selection-change", range, oldRange, source);
        });
        this.quill.on("editor-change", (eventName, ...args) => {
            this.$emit("on-editor-change", eventName, ...args);
        });
    },

    // 点击编辑器中的图片时触发的回调方法
    uploadImage() {
        document.getElementById("picInput").click();
    },

    // 文件输入框失去焦点时,触发的方法
    picChange(e) {
        let file = e.target.files[0];
        let fm = new FormData();
        fm.append("file", file);
        this.postImg(fm).then(res =>{
            // 将返回的可以直接访问的图片路径放回到编辑器中
            let url = res.url;
            const addImageRange = this.quill.getSelection();
            const newRange = 0 + (addImageRange !== null ? addImageRange.index : 0);
            this.quill.insertEmbed(newRange,'image' ,url);
            this.quill.setSection(1 + newRange);
        });
    },

    // 向后台提交图片
    postImg(fm) {
        return new Promise((resolve, reject) =>{
            let self = this;
            let headers = {
                "Content-Type": "multipart/form-data"
            }
            // 如果需要token时,需要此时添加token
            if (token) {
                headers.Authorzation = "Bearer " + token
            }
            axios({
                url: "",
                method: "POST",
                headers: headers,
                data: fm,
            })
            .then(res =>{
                if (res.data.code === 200) {
                    // 根据实际返回的值进行处理
                    resolve(res.data);
                } else {
                    self.$message.error(res.data.msg);
                }
            })
            .catch(err =>{
                self.$message.error(res.data.msg);
            })

        })
    }
  },
};
</script>

<style>
.eidtor {
    min-height: 150px;
    max-height: 500px;
    overflow: auto;
}
.editor, .ql-toolbar {
  white-space: pre-wrap!important;
  line-height: normal !important;
}
.quill-img {
  display: none;
}
.ql-snow .ql-tooltip[data-mode="link"]::before {
  content: "请输入链接地址:";
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0px;
  content: "保存";
  padding-right: 0px;
}

.ql-snow .ql-tooltip[data-mode="video"]::before {
  content: "请输入视频地址:";
}

.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: "14px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
  content: "10px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
  content: "18px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
  content: "32px";
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: "文本";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: "标题1";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: "标题2";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: "标题3";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: "标题4";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: "标题5";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: "标题6";
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: "标准字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
  content: "衬线字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
  content: "等宽字体";
}

</style>

调用的方法:

	<QuillEditor v-model="longText" />
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章