首页 > 技术文章 > quill-editor 富文本插件(含全部全部工具栏)

grootbaby 2020-04-26 15:39 原文

quill-editor 富文本插件

使用

一、npm 安装 vue-quill-editor
二、在main.js中引入

import  VueQuillEditor from 'vue-quill-editor'
// require styles 引入样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

Vue.use(VueQuillEditor)


三、在模块中引用

<template>
     <quill-editor 
      v-model="content" 
      ref="myQuillEditor" 
      :options="editorOption" 
      @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
      @change="onEditorChange($event)">
    </quill-editor>
</template> 
<script>
    import { quillEditor } from 'vue-quill-editor'
    export default{
        data(){
            const toolbarOptions = [['bold', 'italic', 'underline', 'image']];
            return {
                content:null,
                editorOption:{
                    modules:{
                        toolbar:toolbarOptions,
                        theme:'snow',
                    }
                }
            }
        },
        methods:{
            onEditorBlur(){//失去焦点事件
            },
            onEditorFocus(){//获得焦点事件
            },
            onEditorChange(){//内容改变事件
            }
        }
    }
</script>   

 全部工具栏

const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], //加粗,斜体,下划线,删除线
    ['blockquote', 'code-block'],  //引用,代码块


    [{ 'header': 1 }, { 'header': 2 }],  // 标题,键值对的形式;1、2表示字体大小
    [{ 'list': 'ordered'}, { 'list': 'bullet' }],  //列表
    [{ 'script': 'sub'}, { 'script': 'super' }], // 上下标
    [{ 'indent': '-1'}, { 'indent': '+1' }],  // 缩进
    [{ 'direction': 'rtl' }],    // 文本方向

    [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],  //几级标题


    [{ 'color': [] }, { 'background': [] }],  // 字体颜色,字体背景颜色
    [{ 'font': [] }],  //字体
    [{ 'align': [] }], //对齐方式


    ['clean'], //清除字体样式
    ['image','video'] //上传图片、上传视频

];

 

更改图片按钮的事件函数

由于quill插件默认插入图片是base64格式的,若图片较大会引起内容太大无法保存到数据库里面,这样为了上传图片或者插入网络图片,要先更改图片按钮的事件下函数,具体是在editorOption->modules->toolbar中加入handlers对象,并插入名称为image的函数,函数的内容设定为自身所需内容,如下

data () {
  return {
    content: '',
    editorOption: {
      ...
      modules: {
        toolbar: {
          container: toolbarOptions,
          handlers: {
            'image': function (value) {
              if (value) {
                // 自定义内容
              } else {
                this.quill.format('image', false)
              }
            }
          }
        }
      }
    }
  }

修改配置,使图片能够上传到服务器

富文本编辑器中的图片上传是将图片转为base64格式的,如果需要上传图片到服务器,需要修改配置。

创建一个quill-config文件

/*富文本编辑图片上传配置*/
const uploadConfig = {
    action:  '',  // 必填参数 图片上传地址
    methods: 'POST',  // 必填参数 图片上传方式
    token: '',  // 可选参数 如果需要token验证,假设你的token有存放在sessionStorage
    name: 'img',  // 必填参数 文件的参数名
    size: 500,  // 可选参数   图片大小,单位为Kb, 1M = 1024Kb
    accept: 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon'  // 可选 可上传的图片格式
};
 
// toolbar工具栏的工具选项(默认展示全部)
const toolOptions = [
    ['bold', 'italic', 'underline', 'strike'],
    ['blockquote', 'code-block'],
    [{'header': 1}, {'header': 2}],
    [{'list': 'ordered'}, {'list': 'bullet'}],
    [{'script': 'sub'}, {'script': 'super'}],
    [{'indent': '-1'}, {'indent': '+1'}],
    [{'direction': 'rtl'}],
    [{'size': ['small', false, 'large', 'huge']}],
    [{'header': [1, 2, 3, 4, 5, 6, false]}],
    [{'color': []}, {'background': []}],
    [{'font': []}],
    [{'align': []}],
    ['clean'],
    ['link', 'image', 'video']
];
const handlers = {
    image: function image() {
        var self = this;
 
        var fileInput = this.container.querySelector('input.ql-image[type=file]');
        if (fileInput === null) {
            fileInput = document.createElement('input');
            fileInput.setAttribute('type', 'file');
            // 设置图片参数名
            if (uploadConfig.name) {
                fileInput.setAttribute('name', uploadConfig.name);
            }
            // 可设置上传图片的格式
            fileInput.setAttribute('accept', uploadConfig.accept);
            fileInput.classList.add('ql-image');
            // 监听选择文件
            fileInput.addEventListener('change', function () {
                // 创建formData
                var formData = new FormData();
                formData.append(uploadConfig.name, fileInput.files[0]);
                formData.append('object','product');
                // 如果需要token且存在token
                if (uploadConfig.token) {
                    formData.append('token', uploadConfig.token)
                }
                // 图片上传
                var xhr = new XMLHttpRequest();
                xhr.open(uploadConfig.methods, uploadConfig.action, true);
                // 上传数据成功,会触发
                xhr.onload = function (e) {
                    if (xhr.status === 200) {
                        var res = JSON.parse(xhr.responseText);
                        let length = self.quill.getSelection(true).index;
                        //这里很重要,你图片上传成功后,img的src需要在这里添加,res.path就是你服务器返回的图片链接。            
                        self.quill.insertEmbed(length, 'image', res.path);
                        self.quill.setSelection(length + 1)
                    }
                    fileInput.value = ''
                };
                // 开始上传数据
                xhr.upload.onloadstart = function (e) {
                    fileInput.value = ''
                };
                // 当发生网络异常的时候会触发,如果上传数据的过程还未结束
                xhr.upload.onerror = function (e) {
                };
                // 上传数据完成(成功或者失败)时会触发
                xhr.upload.onloadend = function (e) {
                    // console.log('上传结束')
                };
                xhr.send(formData)
            });
            this.container.appendChild(fileInput);
        }
        fileInput.click();
    }
};
 
export default {
    placeholder: '',
    theme: 'snow',  // 主题
    modules: {
        toolbar: {
            container: toolOptions,  // 工具栏选项
            handlers: handlers  // 事件重写
        }
    }
};

引用

<template>
  <div id="Test">
    <quill-editor ref="myQuillEditor" v-model="content" :options="quillOption">
    </quill-editor>
  </div>
</template>
 
<script>
import { quillEditor } from 'vue-quill-editor'
import quillConfig from './quill-config.js'
 
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      content: '<h1>hello quill-editor</h1>',
      quillOption: quillConfig,
    }
  }
}
</script>
 
<style>
</style>

 

推荐阅读