vue-quill-editor 富文本编辑器

分别安装vue-quill-editor 和 quill

npm install vue-quill-editor -S
npm install quill -S
//安装图片大小调整插件
npm install quill-image-resize-module -S

main.js内引用

import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
Vue.use(VueQuillEditor);

在根目录的vue.config.js文件内写入以下内容,如没有就自己创建

// vue.config.js 配置说明
const webpack = require('webpack')
//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions
// 这里只列一部分,具体配置参考文档
module.exports = {
  // 部署生产环境和开发环境下的URL。
  // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上
  //例如 https://www.my-app.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.my-app.com/my-app/,则设置 baseUrl 为 /my-app/。
  //baseUrl 从 Vue CLI 3.3 起已弃用,请使用publicPath
  //baseUrl: process.env.NODE_ENV === "production" ? "./" : "/",
  // publicPath: process.env.NODE_ENV === "production" ? "./" : "/",

  // outputDir: 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)
  //outputDir: "mycli",
  //用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下)
  //assetsDir: "assets",
  //指定生成的 index.html 的输出路径  (打包之后,改变系统默认的index.html的文件名)
  // indexPath: "myIndex.html",
  //默认情况下,生成的静态资源在它们的文件名中包含了 hash 以便更好的控制缓存。你可以通过将这个选项设为 false 来关闭文件名哈希。(false的时候就是让原来的文件名不改变)
  // filenameHashing: false,

  //   lintOnSave:{ type:Boolean default:true } 问你是否使用eslint
  // lintOnSave: true,
  //如果你想要在生产构建时禁用 eslint-loader,你可以用如下配置
  // lintOnSave: process.env.NODE_ENV !== 'production',

  //是否使用包含运行时编译器的 Vue 构建版本。设置为 true 后你就可以在 Vue 组件中使用 template 选项了,但是这会让你的应用额外增加 10kb 左右。(默认false)
  // runtimeCompiler: false,

  /**
   * 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
   *  打包之后发现map文件过大,项目文件体积很大,设置为false就可以不输出map文件
   *  map文件的作用在于:项目打包后,代码都是经过压缩加密的,如果运行时报错,输出的错误信息无法准确得知是哪里的代码报错。
   *  有了map就可以像未加密的代码一样,准确的输出是哪一行哪一列有错。
   * */
  //productionSourceMap: false,

  // 它支持webPack-dev-server的所有选项
  //devServer: {
   // host: "localhost",
    //port: 8081, // 端口号
   // https: false, // https:{type:Boolean}
   // open: true, //配置自动启动浏览器
    // proxy: 'http://47.95.227.250/:8080' // 配置跨域处理,只有一个代理

    // 配置多个代理
    // proxy: {
    //   '/api': {
    //     target: 'http://47.95.227.250/:8080',// 要访问的接口域名
    //     ws: true,// 是否启用websockets
    //     changeOrigin: true, //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
    //     pathRewrite: {
    //         '^/api': ''  //这里理解成用'/api'代替target里面的地址,比如我要调用'http://40.00.100.100:3002/user/add',直接写'/api/user/add'即可
    //       }
    //   }
    // }
  //},
  chainWebpack: config => {
    config.plugin('provide').use(webpack.ProvidePlugin, [{
      'window.Quill': 'quill/dist/quill.js',
      'Quill': 'quill/dist/quill.js'
    }]);
  }
};

在src/components 文件夹内新建 quill.vue 文件

<template>
  <div v-loading.fullscreen.lock="quillUpdateImg">
    <!-- 图片上传组件辅助-->
    <el-upload
      style="height: 0;"
      class="img-uploader"
      :action="globalAPI.postUpload"
      :show-file-list="false"
      :multiple="false"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :before-upload="beforeUpload">
    </el-upload>
    <!-- 图片上传组件辅助-->
    <!-- 视频上传组件辅助-->
    <el-upload
      style="height: 0;"
      class="video-uploader"
      :action="globalAPI.postUpload"
      :show-file-list="false" 
      :multiple="false" 
      :on-success="videouploadSuccess" 
      :on-error="videoUploadError" 
      :before-upload="videoBeforeUpload">
    </el-upload>
    <!-- 视频上传组件辅助-->
    <!-- 音频上传组件辅助-->
    <el-upload
      style="height: 0;"
      class="audio-uploader"
      :action="globalAPI.postUpload"
      :headers="header"
      :show-file-list="false"
      :multiple="false"
      :on-success="audioUploadSuccess"
      :on-error="audioUploadError"
      :before-upload="audioBeforeUpload">
    </el-upload>
    <!-- 音频上传组件辅助-->
    <!--quill 核心组件-->
    <quill-editor
      class="editor"
      v-model="$store.state.content"
      ref="myQuillEditor"
      :options="editorOption"
      @blur="onEditorBlur($event)"
      @focus="onEditorFocus($event)"
      @change="onEditorChange($event)">
    </quill-editor>
    <!--quill 核心组件-->
  </div>
</template>
<script>
  import { quillEditor , Quill } from "vue-quill-editor";
  import { Quill } from "vue-quill-editor";

  import ImageResize from 'quill-image-resize-module'; //引用图片裁剪插件
  Quill.register('modules/imageResize', ImageResize) //引用图片裁剪插件

  let fonts = ['Microsoft-YaHei', 'SimSun', 'SimHei', 'KaiTi', 'Arial']; //添加字体
  let Font = Quill.import('formats/font'); //添加字体
  Font.whitelist = fonts; //添加字体

  let fontSizeStyle = Quill.import('attributors/style/size'); //添加字号
  fontSizeStyle.whitelist = ['12px', '14px', '16px', '18px', '22px', '26px', '30px', '36px', '42px', '60px'] //添加字号
  Quill.register(fontSizeStyle, true); //添加字号

  let Align = Quill.import('attributors/style/align'); //文字对齐
  Align.whitelist = ['right', 'center', 'justify']; //文字对齐
  Quill.register(Align, true); //文字对齐
    // 工具栏配置
  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': fontSizeStyle.whitelist
    }], // 字体大小
    [{
      header: [1, 2, 3, 4, 5, 6, false]
    }], // 标题
    [{
      color: []
    }, {
      background: []
    }], // 字体颜色、字体背景颜色
    [{
      'font': fonts
    }], // 字体种类
    [{
      align: []
    }], // 对齐方式
    ["clean"], // 清除文本格式
    ["link", "image", "video","audio"], // 链接、图片、视频
  ];
  export default {
    components: {
      quillEditor
    },
    data() {
      return {
        content :'',
        quillUpdateImg: false,
        editorOption: {
          theme: "snow", // or 'bubble'
          placeholder: "您想说点什么?",
          modules: {
            toolbar: {
              container: toolbarOptions,
              handlers: {
                image: function(value) {
                  if (value) {
                    // 触发input框选择图片文件
                    document.querySelector(".img-uploader input").click();
                  } else {
                    this.quill.format("image", false);
                  }
                },
                video: function(value) {
                  if (value) {
                    // 触发input框选择图片文件
                    document.querySelector(".video-uploader input").click();
                  } else {
                    this.quill.format("video", false);
                  }
                },
                'audio': function() { //添加工具方法,即点击时模仿点击上传组件的按钮
                  document.querySelector('.audio-uploader input').click()
                }
              },
            },
            imageResize: {
              displayStyles: {
                backgroundColor: 'black',
                border: 'none',
                color: 'white'
              },
              modules: ['Resize', 'DisplaySize', 'Toolbar']
            }
          }
        },
        serverUrl: "", // 这里写你要上传的图片服务器地址
        header: {}
      }
    },
    mounted() {
      this.content = this.$store.state.content
    },
    methods: {
      onEditorBlur() {
        //失去焦点事件
      },
      onEditorFocus() {
        //获得焦点事件
      },
      onEditorChange() {
        //内容改变事件
        this.$emit("input", this.content);
      },
      //音频上传校验
      AbeforeUpload(file) {
        let testmsg = file.name.substring(file.name.lastIndexOf('.') + 1);
        const extension = testmsg === 'mp3' || testmsg === 'wav' || testmsg === 'MP3' || testmsg === 'WAV';
        if (!extension) {
          this.$message({
            message: '上传音频只能是 mp3 / wav 格式!',
            type: 'error'
          });
          return false; //必须加上return false; 才能阻止
        }
        let testsize = file.size / 1024 / 1024 < 80
        if (!testsize) {
          this.$message({
            message: '上传音频大小不能超过 80MB!',
            type: 'warning'
          });
          return false;
        }
        this.quillUpdateImg = true;
        return extension && testsize
      },
      //视频上传校验
      VbeforeUpload(file) {
        let testmsg = file.name.substring(file.name.lastIndexOf('.') + 1);
        const extension = testmsg === 'mp4' || testmsg === 'MP4' || testmsg === 'avi' || testmsg === 'AVI';
        if (!extension) {
          this.$message({
            message: '上传视频只能是 mp4 / avi 格式!',
            type: 'error'
          });
          return false; //必须加上return false; 才能阻止
        }
        let testsize = file.size / 1024 / 1024 < 500
        if (!testsize) {
          this.$message({
            message: '上传视频大小不能超过 500MB!',
            type: 'warning'
          });
          return false;
        }
        this.quillUpdateImg = true;
        return extension && testsize
      },
      // 富文本图片上传校验
      beforeUpload(file) {
        let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
        // var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
        const extension =
          testmsg === "jpg" ||
          testmsg === "JPG" ||
          testmsg === "png" ||
          testmsg === "PNG"
        if (!extension) {
          this.$message({
            message: "上传图片只能是jpg / png 格式!",
            type: "error"
          });
          return false; //必须加上return false; 才能阻止
        }
        let testsize= file.size / 1024 / 1024 < 2
        if (!testsize) {
          this.$message({
            message: '上传文件大小不能超过 2MB!',
            type: 'warning'
          });
          return false;
        }
        // 显示loading动画
        this.quillUpdateImg = true;
        return extension && testsize
      },
      //图片上传成功
      uploadSuccess(res) {
        // res为图片服务器返回的数据
        // 获取富文本组件实例
        // console.log(res, '1')
        let quill = this.$refs.myQuillEditor.quill;
        // 如果上传成功
        if (res.code == 10000) {
          // 获取光标所在位置
          let length = quill.getSelection().index;
          // 插入图片  res.url为服务器返回的图片地址
          quill.insertEmbed(length, "image", res.data);
          // 调整光标到最后
          quill.setSelection(length + 1);
        } else {
          this.$message.error("图片插入失败");
        }
        // loading动画消失
        this.quillUpdateImg = false;
      },
      //视频上传成功
      VuploadSuccess(res) {
        // res为视频服务器返回的数据
        // 获取富文本组件实例
        // console.log(res)
        let quill = this.$refs.myQuillEditor.quill;
        // 如果上传成功
        if (res.code == 10000) {
          // 获取光标所在位置
          let length = quill.getSelection().index;
          // 插入视频  res.url为服务器返回的视频地址
          quill.insertEmbed(length, "video", res.data);
          // 调整光标到最后
          quill.setSelection(length + 1);

        } else {
          this.$message.error("视频插入失败");
        }
        // loading动画消失
        this.quillUpdateImg = false;
      },
      //音频上传成功
      AuploadSuccess(res) {
        this.quillUpdateImg = false;
        // 获取富文本组件实例
        let quill = this.$refs.myQuillEditor.quill
        if (res.code === 10000) { // 如果上传成功
          let length = quill.getSelection().index; // 获取光标所在位置
          // insertEmbed(index: Number(插入的位置), type: String(标签类型), value: any(参数,将传入到create的方法中去), source: String = 'api')
          quill.insertEmbed(length, 'audio', res.data);
          quill.setSelection(length + 1); //光标位置向后移动一位
        } else {
          this.$message.error(res.msg); // 上传失败,提示错误信息
        }
      },
      // 富文本图片上传失败
      uploadError() {
        // loading动画消失
        this.quillUpdateImg = false;
        this.$message.error("图片插入失败");
      },
      // 富文本视频上传失败
      VuploadError() {
        // loading动画消失
        this.quillUpdateImg = false;
        this.$message.error("视频插入失败");
      },
      // 富文本音频上传失败
      AuploadError() {
        // loading动画消失
        this.quillUpdateImg = false;
        this.$message.error("音频插入失败");
      },
    }
  }
</script>
<style>
/*汉化以及自定义*/
  .editor {
    line-height: normal !important;
    height: 600px;
  }

  .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-container.ql-snow {
    height: 535px;
  }
    .ql-snow .ql-tooltip[data-mode=video]::before {
    content: "请输入视频地址:";
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="14px"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="14px"]::before {
    content: '14px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="12px"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="12px"]::before {
    content: '12px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="16px"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="16px"]::before {
    content: '16px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="18px"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="18px"]::before {
    content: '18px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="22px"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="22px"]::before {
    content: '22px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="26px"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="26px"]::before {
    content: '26px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="30px"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="30px"]::before {
    content: '30px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="36px"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="36px"]::before {
    content: '36px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="42px"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="42px"]::before {
    content: '42px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="60px"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="60px"]::before {
    content: '60px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="14px"]::before {
    font-size: 14px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="12px"]::before {
    font-size: 12px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="16px"]::before {
    font-size: 16px';

  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="18px"]::before {
    font-size: 18px';

  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="22px"]::before {
    font-size: 22px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="26px"]::before {
    font-size: 26px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="30px"]::before {
    font-size: 30px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="36px"]::before {
    font-size: 36px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="42px"]::before {
    font-size: 42px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="60px"]::before {
    font-size: 60px;
  }
</style>

另外需要配合修改一些CSS和JS文件。
链接:https://pan.baidu.com/s/1aMXfU1ubrOY25EketrTzEA
提取码:eanj

需要使用的文件内引用此VUE文件即可

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 进入大厂的面试经验(P7)个人近期面试情况今年二月以来,我的面试除了一个用友的,基本其他都被毙了,可以说是非常残酷...
    半眼鱼阅读 401评论 0赞 1
  • JS 一.javaScript HTML:写网页 CSS:美化页面 javaScript:页面的行为 javaS...
    提笔执江山阅读 94评论 0赞 0
  • JS 一、javaScript 是什么?有什么作用? HTML:写网页的 人的身体 CSS: 美化页面的 人的衣服...
    请重置阅读 166评论 0赞 0
  • CSS简述 HTML》》页面的结构》》 人的面部 CSS》》 美化页面》》 给人化妆 CSS:层叠样式表 层叠:一...
    提笔执江山阅读 104评论 0赞 0
  • Ubuntu分区方案(菜鸟方案、常用方案和进阶方案) 原创 春鸽带你飞 https://blog.csdn.net...
    分手吧刘亦菲阅读 162评论 0赞 0

友情链接更多精彩内容