Vue使用Quill富文本编辑器

最近在做的项目中使用到了富文本编辑器,遂决定使用Quill。Quill官方没有提供Vue支持,找到了一个第三方库 Vue-Quill-Editor提供了支持,链接如下:

vue-quill-editor(gitee)
vue-quill-editor(github.com)

我并没有使用全局注册,仅在某个组件里使用了这个组件,以下为配置代码:

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import Quill from 'quill'
import {quillEditor} from 'vue-quill-editor'
import ImageResize from 'quill-image-resize-module'
import {ImageDrop} from 'quill-image-drop-module'

Quill.register('modules/imageResize', ImageResize)
Quill.register('modules/imageDrop', ImageDrop)

export default {
  components: {quillEditor},
  data() {
    return {
      announcementContent: '',
      editorOption: {
        placeholder: '请输入公告内容',
        modules: {
          toolbar: {
            container: [
              ['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'],
              ['image', 'link']
            ]
          },
          imageResize: {
          },
          imageDrop:true
        }
      }
    }
  }
}

具体的配置参考实际使用的,这里给出的是我自己的配置。

因为实际使用必须要支持图片插入和图片的大小编辑,于是用到了Quill的两个模块quill-image-resize-module、quill-image-drop-module,都是支持webpack的,所以直接npm安装然后按照上述代码配置使用即可。

在引入这两个模块的时候出现了两个问题:
Cannot read property ‘imports’ of undefined
Cannot read property ‘register’ of undefined

这两个问题查了很多资料,最后综合得出了一个解决方案。首先在webpack配置中加入以下代码,这里我用的是vue-cli4,所以写在了vue.config.js里:

const webpack = require("webpack");
module.exports = {
    configureWebpack: {
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules(?!\/quill-image-drop-module|quill-image-resize-module)/,
                    loader: 'babel-loader',
                    query: {...}
                }
            ]
        },
        plugins: [
            new webpack.ProvidePlugin({
                'window.Quill': 'quill/dist/quill.js',
                'Quill': 'quill/dist/quill.js',
            })
        ]
    }
}

一开始加入这段代码后解决了Cannot read property ‘imports’ of undefined这个报错,但是却出现了Cannot read property ‘register’ of undefined报错,最后查了很久发现一开始的组件引用代码这里是这样写的:

import {ImageResize} from 'quill-image-resize-module'
import { ImageDrop } from 'quill-image-drop-module'

把ImageResize的括号去了就正常了。。。真是蛮无语的一个问题,希望这个解决方案对其他人能有所帮助

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Captcha Code