• vue-quill-editor 修改配置,和图片上传


    富文本编辑器中的图片上传是将图片转换成Base64格式的,如果需要将图片上传至自己的图片服务器,需要修改配置

    quillEditor/quill-config.js

    /*富文本编辑图片上传配置*/
    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  // 事件重写
            }
        }
    };

    上述是通用模式,根据需要修改 uploadConfig 中的内容,以及修改 ajax 的内容

    下面是某次使用

    import $http from '@/common/request/ajax' // 这里使用axios封装了http请求
    import API from '@/common/request/api' // 接口API
    
    /* 富文本编辑图片上传配置 */
    const uploadConfig = {
      name: 'img', // 必填参数 文件的参数名
      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', async () => {
            const formData = new FormData()
            formData.append('file', fileInput.files[0])
            let res = await $http.post(API.uploadFile, formData)
            let length = 0
            if (res.code === '0') { // 相当于接口成功回调
              length = self.quill.getSelection(true).index
            }
            self.quill.insertEmbed(length, 'image', res.data.picUrl)
            self.quill.setSelection(length + 1)
            fileInput.value = ''
          })
          this.container.appendChild(fileInput)
        }
        fileInput.click()
      }
    }
    
    export default {
      placeholder: '',
      theme: 'snow', // 主题
      modules: {
        toolbar: {
          container: toolOptions, // 工具栏选项
          handlers: handlers // 事件重写
        }
      }
    }

    页面:quillEditor/index.vue

    <template>
      <div>
        <quill-editor ref="myTextEditor"
          :value="value"
          :options="quillOption"
          @input="input"
          @blur="onEditorBlur($event)"
          @focus="onEditorFocus($event)"
          @change="onEditorChange($event)">
        </quill-editor>
      </div>
    </template>
    
    <script>
    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 quillConfig from './quill-config.js'
    
    export default {
      props: ['value'],
      components: {
        quillEditor
      },
      data () {
        return {
          quillOption: quillConfig
        }
      },
      methods: {
        input (val) {
          this.$emit('input', val)
        },
        onEditorBlur (e) { // 失去焦点事件
          this.$emit('blur', e)
        },
        onEditorFocus (e) { // 获取焦点事件
          this.$emit('focus', e)
        },
        onEditorChange (e) { // change事件
          this.$emit('change', e)
        }
      }
    }
    </script>

    组件使用:这里就可以使用v-model了

    <template>
      <div>
        <myQuillEditor v-model="content" @blur="onEditorBlur"></myQuillEditor>
      </div>
    </template>
    <script>
    import myQuillEditor from '@/components/tool/quillEditor'
    export default {
      data() {
        return {
          content: ``
        }
      },
      methods: {
        onEditorBlur(e) {  // 失去焦点事件
          this.innerValid() // 失去焦点时进行业务验证---这里可以去掉
          console.log(e)
        },
      }
      watch: {
        content(newVal){ // 查看内容改变时value的变化---这里可以去掉
          console.log(newVal)
        }
      },
      components: {
        myQuillEditor
      }
    }
    </script>

    根据需求,可以修改编辑器的工具栏

    <quill-editor
      style="height:100px"
      v-model="contentFY"
      ref="myQuillEditorFY"
      :options="editorOptionFY"
      @blur="onEditorBlurFY($event)" @focus="onEditorFocusFY($event)"
      @change="onEditorChangeFY($event)">
    </quill-editor>
    editorOption: {
      modules:{
        toolbar:[
          ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
          ['blockquote', 'code-block']
        ]
      },
      placeholder: '请输入内容及工作量',
    }

    那么toolbar工具栏对应功能的模块名

    背景颜色 - background
    加粗- bold
    颜色 - color
    字体 - font
    内联代码 - code
    斜体 - italic
    链接 - link
    大小 - size
    删除线 - strike
    上标/下标 - script
    下划线 - underline
    引用- blockquote
    标题 - header
    缩进 - indent
    列表 - list
    文本对齐 - align
    文本方向 - direction
    代码块 - code-block
    公式 - formula
    图片 - image
    视频 - video
    清除字体样式- clean

  • 相关阅读:
    【CF446D】DZY Loves Games 高斯消元+矩阵乘法
    【CF542D】Superhero's Job 暴力
    【CF660E】Different Subsets For All Tuples 结论题
    【CF666C】Codeword 结论题+暴力
    【CF666E】Forensic Examination 广义后缀自动机+倍增+线段树合并
    【CF461E】Appleman and a Game 倍增floyd
    【CF471E】MUH and Lots and Lots of Segments 扫描线+并查集+线段树+set
    【CF480D】Parcels DP
    【CF497E】Subsequences Return 矩阵乘法
    SSAS 项目部署失败的问题
  • 原文地址:https://www.cnblogs.com/haishen/p/11840181.html
Copyright © 2020-2023  润新知