vue-quill-editor富文本编辑器

由于我们在项目中使用的次数不会很多,这里将作为按需引入方式使用。

富文本编辑器-效果展示

安装依赖

npm install vue-quill-editor --save

创建 VueQuillEditor.js

import Vue from 'vue'
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)

创建 titleConfig.js(可不添加)

// 文本提示语
export 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-list": "列表",
    "ql-align": "文本对齐",
    "ql-direction": "文本方向",
    "ql-code-block": "代码块",
    "ql-formula": "公式",
    "ql-image": "图片",
    "ql-video": "视频",
    "ql-clean": "清除字体样式",
    "ql-upload": "文件"
};

按需引入方式

1.html

<el-upload
    v-show="false"
    class="upload-demo"
    :action="uploadImgUrl"
    :headers="uploadHeaders"
    accept="image/jpeg,image/png,image/bmp"
    :before-upload="handleBeforeUpload"
    :on-success="handleSuccess"
    :show-file-list="false"
>
    <el-button v-show="false" class="ivu-btn" size="small" type="primary"></el-button>
</el-upload>
<quill-editor class="ql-editor"
    v-model="content"
    ref="QuillEditor"
    :options="editorOption"
    @blur="onEditorBlur($event)"
    @focus="onEditorFocus($event)"
    @change="onEditorChange($event)"
></quill-editor>

2.javaSrcipt

import '@/assets/js/quillEditor/VueQuillEditor.js'
import { titleConfig } from '@/assets/js/quillEditor/titleConfig.js' // 富文本文本提示语
export default {
    data() {
        return {
            fileSize: 10,
            uploadHeaders: { // 图片上传接口请求头
                Authorization: "token",
                Platform: "web",
            },
            uploadImgUrl: "/upload", // 上传的图片服务器地址
            content: "",
            editorOption: {
                placeholder: '请在这里输入',
                modules: {
                    toolbar: {
                        container: [
                            ['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']    //上传图片
                            // ['image','video','link']    //上传图片、上传视频、上传文件
                        ],
                        handlers: {
                            'image': function (value) {
                                if (value) {
                                    // 调用iview图片上传
                                    document.querySelector('.upload-demo .ivu-btn').click()
                                } else {
                                    this.quill.format('image', false);
                                }
                            }
                        }
                    }
                }
            },
        }
    },
    // 在dom创建完成后再调用
    mounted() {
        // 富文本提示信息
        this.$nextTick(() => {
            const oToolBar = document.getElementsByClassName('ql-editor')[0];
            const aButton = oToolBar.querySelectorAll('button');
            const 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]];
            });
        })
    },
    methods: {
        onEditorBlur(e){
            console.log(e, '失去焦点事件');
        },
        onEditorFocus(e){
            console.log(e, '获得焦点事件');
        },
        onEditorChange(e){
            console.log(e, '内容改变事件');
        },
        // 上传前校检格式和大小
        handleBeforeUpload(file) {
            // 检验文件类型
            const isIMAGE = (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/bmp');
            if (!isIMAGE) {
                this.$message.error(`请上传图片类型文件!`);
                return false;
            }
            // 校检文件大小
            const isLt = file.size / 1024 / 1024 < this.fileSize;
            if (!isLt) {
                this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
                return false;
            }
            return true;
        },
        handleSuccess (res) {
            // 获取富文本组件实例
            let quill = this.$refs.QuillEditor.quill
            // 如果上传成功
            if (res.code===0) {
                // 获取光标所在位置
                let length = quill.getSelection().index;
                // 插入图片,res为服务器返回的图片链接地址
                quill.insertEmbed(length, 'image', res.data)
                // 调整光标到最后
                quill.setSelection(length + 1)
            } else {
                // 提示信息,需引入Message
                this.$message.error('图片插入失败')
            }
        },
    }
}

编辑后成功返回

console.log(this.content);
解决图片上传后的 html 模板转码失败(看需求,非必须)
  • 【UrlEncode编码/UrlDecode解码】
encodeURIComponent(this.content); // 编码
decodeURIComponent(this.content); // 解码
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容