vue+element-ui中引入wangeditor编辑器

1.执行:npm install  --save  wangeditor

2.在你需要调用编辑器的vue文件中引入 wangeditor:

import E from 'wangeditor'

页面调用:

<div id="editor">
    <!--<p>{{addFormData.content?'请输入正文':addFormData.content}}  </p>-->
</div>

初始化编辑器:

在 mounted 方法中:

that.$nextTick(function () {
                // Code that will run only after the
                // entire view has been rendered
                // 创建编辑器
                that.editor = new E('#editor')
                // 自定义菜单配置
                that.editor.customConfig.menus = [
                    'bold',// 粗体
                    'italic',// 斜体
                    'head',// 标题
                    'quote',  // 引用
                    'list',  // 列表
                    'link',  // 插入链接
                    'image',  // 插入图片
                    'table',  // 表格
                ]
                that.editor.customConfig.onchange = function (html) {
                    if (html.replace(/<\/?[^>]+>/g, '')!=="") {
                        that.addFormData.content = html
                        that.$refs['addForm'].validateField('content')
                    }
                    // html 即变化之后的内容
                    // console.log(html)
                }
                // 配置服务器端地址
                that.editor.customConfig.uploadImgServer = that.uploadUrl
                // 将图片大小限制为 1M
                that.editor.customConfig.uploadImgMaxSize = 1 * 1024 * 1024
                // 限制一次最多上传 1 张图片
                that.editor.customConfig.uploadImgMaxLength = 1
                that.editor.customConfig.uploadFileName = 'file'; //设置文件上传的参数名称
                that.editor.customConfig.uploadImgHooks = {
                    customInsert: function (insertImg, result, editor) {
                        // 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!)
                        // insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果
                        // 举例:假如上传图片成功后,服务器端返回的是 {url:'....'} 这种格式,即可这样插入图片:
                        if (result.code === 200) {
                            insertImg(that.imgSrc + result.data.id)
                        }
                        // var url = result.url
                        // insertImg(url)
                        // result 必须是一个 JSON 格式字符串!!!否则报错
                    }
                }
                that.editor.create()
                that.editor.txt.html(that.addFormData.content ? that.addFormData.content : '')
                // 禁用
                if (that.addFormData.disabled) {
                    // that.editor.disable();
                    that.editor.$textElem.attr('contenteditable', false)
                }
            })

 注意:

小颖之所以把初始化编辑器写在 $nextTick 内,是因为小颖调用编辑器时是在 el-dialog 组件中调用的,如果直接在 mounted 下初始化时,它始终不出来。

猜你喜欢

转载自www.cnblogs.com/yingzi1028/p/12809087.html