zoukankan      html  css  js  c++  java
  • vue-quill-editor + iview 实现富文本编辑器及图片上传

    1、npm 安装 vue-quill-editor 

    npm install vue-quill-editor

    2、再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)

    3、创建子组件UE.vue

    <template>
      <div>
        <Upload
          :show-upload-list="false"
          class="editor_upload"
          :format="['jpg','jpeg','png']"
          :max-size="2048"
          multiple
          :before-upload="handleUpload"
          action="//jsonplaceholder.typicode.com/posts/"
        >
          <Button icon="ios-cloud-upload-outline" ></Button>
        </Upload>
        <quill-editor
          v-model="msg"
          :options="editorOption"
          ref="QuillEditor">
        </quill-editor>
      </div>
    </template>
    <script>
      import {PostBase64Upload} from '../../../services/pages/market'
      //工具
      const toolbarOptions = [
        ['bold', 'italic', 'underline', 'strike','blockquote', 'code-block',{'indent': '-1'}, {'indent': '+1'},{'color': []}, {'background': []},{'align': []},'image','clean'],        // toggled buttonssuperscript/subscript
      ];
      //工具名称
      const titleConfig = {
        'ql-bold':'加粗',
        'ql-color':'颜色',
        'ql-font':'字体',
        'ql-code':'插入代码',
        'ql-italic':'斜体',
        'ql-link':'添加链接',
        'ql-background':'背景颜色',
        'ql-size':'字体大小',
        'ql-strike':'删除线',
        'ql-script':'上标/下标',
        'ql-underline':'下划线',
        'ql-blockquote':'引用',
        'ql-header':'标题',
        'ql-indent':'缩进',
        'ql-align':'文本对齐',
        'ql-direction':'文本方向',
        'ql-code-block':'代码块',
        'ql-image':'图片',
        'ql-video':'视频',
        'ql-clean':'清除字体样式',
      };
      export default {
        name: 'UE',
        data () {
          return {
            IMAGE_URL: global.IMG_URL,
            QuillEditor: null,
            editorOption: {
              modules: {
                toolbar: {
                  container: toolbarOptions,  // 工具栏
                  handlers: {
                    'image': function (value) {
                      if (value) {
                        document.querySelector('.ivu-upload .ivu-btn').click()
                      } else {
                        this.quill.format('image', false);
                      }
                    }
                  }
                }
              }
            },
            file_url: '',
            importFile: '',
            msg: ''
          }
        },
        props: ["defaultMsg",],
        mounted() {
          this.msg = this.defaultMsg;
          this.addQuillTitle()
        },
        methods: {
          // 提交文件并阻断自动上传
          handleUpload(file) {
            let that = this;
            let time = setTimeout(function () {
              that.upload(file);
              clearTimeout(time);
            }, 0);
            return false
          },
          //上传图片
          upload(file) {
            let index = file.name.lastIndexOf(".");
            let file_url = file.name.substring(index + 1, file.name.length);
            if (file_url == 'jpg' || file_url == 'jpeg' || file_url == 'png' ) {
              let that = this;
              let reader = new FileReader();
              reader.readAsDataURL(file);
              reader.onload = function (e) {
                PostBase64Upload({
                  base64_content: e.target.result,
                  module_name: 'topic'
                })
                  .then(data => {
                    that.file_url = data.file_url;
                    that.handleSuccess(that.file_url)
                  })
                  .catch(err => {
                    that.$Message.error(err);
                  });
                return false;
              };
            } else {
              this.$Message.error("请上传'jpg','jpeg', png'格式的图片");
              return false;
            }
          },
    
          //图片加入到富文本框中
          handleSuccess (res) {
            let quill = this.$refs.QuillEditor.quill;
            let length = quill.getSelection().index;
            quill.insertEmbed(length, 'image', res)
            quill.setSelection(length + 1);
            this.msg = this.getImgSrc(this.msg);
          },
          //加入路径的IP
          getImgSrc(content) {
            // 正则替换img的路径
            let that = this;
            content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
              content = content.replace(new RegExp(capture, 'g'), that.IMAGE_URL + capture);//这里也可以替换成需要的路径
            });
            content = content.replace(/<img/g, '<img style=" 100%;"');
            return content;
          },
    
          //富文本工具添加名称
          addQuillTitle () {
            const oToolBar = document.querySelector('.ql-toolbar'),
              aButton = oToolBar.querySelectorAll('button'),
              aSelect =  oToolBar.querySelectorAll('select');
            aButton.forEach(function(item){
              if(item.className === 'ql-script'){
                item.value === 'sub' ? item.title = '下标': item.title = '上标';
              }else if(item.className === 'ql-indent'){
                item.value === '+1' ? item.title ='向右缩进': item.title ='向左缩进';
              }else{
                item.title = titleConfig[item.classList[0]];
              }
            });
            aSelect.forEach(function(item){
              item.parentNode.title = titleConfig[item.classList[0]];
            });
          },
        },
      }
    </script>
    <style>
      .editor_upload {
        display: none;
      }
    </style>

    4、引入该组件页面

     <UE :defaultMsg=defaultMsg ref="ue"></UE>
    
    <script>
        import UE from "./UE"
        //因子组件不能修改父组件的参数,所以父组件提交时,直接调取子组件的参数
        this.$refs.ue.msg
    </script>

    上述的工具栏是根据我司的要求来选择的,如果你想需求的更多,我也是查看别的大神的,你也可以看看https://blog.csdn.net/div_ma/article/details/79536634

  • 相关阅读:
    最简单跳转,待反混爻的合集
    搜索引擎劫持代码
    Warning: Cannot modify header information
    editplus 正则删换行
    在全程Linux環境部署IBM Lotus Domino/Notes 8.5
    3.5-杂项②
    3.4-杂项①
    3.3-ISDN
    3.2-帧中继②
    3.2-帧中继①
  • 原文地址:https://www.cnblogs.com/mxyr/p/11024347.html
Copyright © 2011-2022 走看看