背景:业务需求,要实现一个富文本框,好方便用户插入图片

问题:百度了一整天,看了n多文章包括官方文档,又花了半天时间实现需求,对于小白来说,真的是大难题,又着急,又害怕,结果就是,越急越搞不定……此处省略我的吐槽

来吧,上步骤:

一、安装富文本 wangEditor(参考官方文档)wangEditor

npm install wangeditor --save

我这里装的是版本4 (因为我折腾了半天的版本5 没搞出来)

二、在components文件夹下新建一个Vue文件,名字随便。参考:wangEditor.vue

把下面代码复制粘贴进去(图片上传部分还没完善好)

<template>
    <div>
        <div id="websiteEditorElem" style="height:300px;background: #ffffff;"></div>
    </div>
</template>
<script>
import E from 'wangeditor'
export default {
    name: "wangEditor",
    props: {
        content: "" //获取从父组件中传过来的值,主要用于修改的时候获取值,并加入到富文本框中
    },
    data() {
        return {
            phoneEditor: '',
            name: '',
        }
    },
    methods: {
    },
    mounted() {
        this.phoneEditor = new E('#websiteEditorElem')
        // 上传图片到服务器,base64形式
        this.phoneEditor.config.uploadImgShowBase64 = true
        // // 隐藏网络图片
        this.phoneEditor.config.showLinkImg = false;
        this.phoneEditor.config.debug = true;
        //图片上传接口
        this.phoneEditor.config.uploadImgServer = '' // 上传图片的接口地址
        this.phoneEditor.config.uploadFileName = 'image' // formdata中的name属性,比如现在是将图片image加入到formdate,后台从image中接收到图片数据
        this.phoneEditor.config.uploadImgHeaders = {
            token: sessionStorage.getItem("token") // 设置请求头
        }
        this.phoneEditor.config.uploadImgHooks = {
            customInsert: function (insertImg, result, editor) {
                console.log("成功", result);
                // before: function (xhr, editor, files) {
                //     // 图片上传之前触发
                //     // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,files 是选择的图片文件
                //     // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
                //     // return {
                //     //     prevent: true,
                //     //     msg: '放弃上传'
                //     // }
                // },
                // success: function (xhr, editor, result) {
                //     // 图片上传并返回结果,图片插入成功之后触发
                //     // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
                // },
                // fail: function (xhr, editor, result) {
                //     // 图片上传并返回结果,但图片插入错误时触发
                //     // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
                // },
                // error: function (xhr, editor) {
                //     // 图片上传出错时触发
                //     // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象
                // },
                // timeout: function (xhr, editor) {
                //     // 图片上传超时时触发
                //     // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象
                // },
                // // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式,可使用该配置
                // // (但是,服务器端返回的必须是一个 JSON 格式字符串!!!否则会报错)
                // customInsert: function (insertImg, result, editor) {
                //     // 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!)
                //     // insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果
                //     // 举例:假如上传图片成功后,服务器端返回的是 {url:'....'} 这种格式,即可这样插入图片:
                //     var url = result.url
                //     insertImg(url)
                //     // result 必须是一个 JSON 格式字符串!!!否则报错
                // }
            }
        }
        // 创建一个富文本编辑器
        this.phoneEditor.create()
        // 修改的时候,需要富文本内容回显,则需要加入以下代码
        this.phoneEditor.txt.html(this.content)
        this.phoneEditor.config.onchange = (html) => {
            this.info_ = html // 绑定当前逐渐地值
            this.$emit('change', this.info_) // 将内容同步到父组件中
        }
    },
}
</script>

步骤分解:

将内容同步到父组件中:

 this.phoneEditor.config.onchange = (html) => {
            this.info_ = html // 绑定当前逐渐地值
            this.$emit('change', this.info_) // 将内容同步到父组件中
        }

父组件中的获取方法是

<WangEdit @change="grtUrl" :content="editForm.content"></WangEdit>

@change="getUrl1"获取子组件中的数据,具体方法如下:

grtUrl(path){
            this.editForm.content = path;
        },

将子组件的数据加入到this.editForm.content中

修改内容时

需要富文本框中的数据回显,在子组件中加入

props:{
        content:"" //获取从父组件中传过来的值,主要用于修改的时候获取值,并加入到富文本框中
      },

三、从父组件中调用子组件时

完整代码:

<el-dialog title="修改培训信息" v-model="editWinVisible" width="45%" :before-close="handleClose" :center="false">
        <el-row class="dialog-detail">
            <el-col :span="5" class="dialog-detail-title">培训编号:</el-col>
            <el-col :span="19" class="dialog-detail-content">{{editForm.code}}</el-col>
            <el-col :span="5" class="dialog-detail-title">培训标题:</el-col>
            <el-col :span="19" class="dialog-detail-content">
                <el-input v-model="editForm.title" placeholder="请输入培训标题"></el-input>
            </el-col>
            <el-col :span="5" class="dialog-detail-title">培训内容:</el-col>
            <el-col :span="19" class="dialog-detail-content" >
                <WangEdit @change="grtUrl" :content="editForm.content"></WangEdit>
            </el-col>
            <el-col :span="5" class="dialog-detail-title">创建时间:</el-col>
            <el-col :span="19" class="dialog-detail-content">
                {{editForm.createDate}}
            </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
            <el-button @click="CloseWin()">关闭</el-button>
            <el-button type="primary" @click="SaveEditData()">保存</el-button>
        </span>
    </el-dialog>
<script>
import WangEdit from '@/components/wangEditor.vue' //WangEditor在项目中的地址
import Req from '@/utils/ApiRequest'
export default{
    components:{ WangEdit },
    data(){
        return{
            editForm:{content:''},
            editWinVisible:false,
         }
    },
    methods:{
        grtUrl(path){
            this.editForm.content = path;
        },
        SaveEditData(){
            console.log('send',this.editForm)
            //下面这行代码就是控制页面显示是否带<p>标签的
            //this.editForm.content=this.editForm.content.replace(/<[^>]+>/g,"")
            Req.UpdateNews(this.editForm).then((res)=>{
                if(res.status==200)
                {
                    this.$message({type: 'success', message: '保存成功!'});
                    this.CloseWin();
                    this.GetTabData();
                }
                else{
                    this.$message({type: 'error', message: '保存失败!'});          
                }
            })
        },
    }
}

 富文本框就好了,数据也绑上了

【更新】vue使用 wangeditor4 富文本 + 富文本回显带标签+wangEditor4 加字数,光标会跑到最后 问题 (已解决)

 注意:接下来,出现了一个bug,我在文本框里编辑后,页面绑定的数据神奇的带上了标签:

【更新】vue使用 wangeditor4 富文本 + 富文本回显带标签+wangEditor4 加字数,光标会跑到最后 问题 (已解决)

 【更新】vue使用 wangeditor4 富文本 + 富文本回显带标签+wangEditor4 加字数,光标会跑到最后 问题 (已解决)

 好了,接下来又是一顿百度,还好让我找到了

使用富文本quill-editor发送后台数据有标签问题<p>

【更新】vue使用 wangeditor4 富文本 + 富文本回显带标签+wangEditor4 加字数,光标会跑到最后 问题 (已解决)

在点击确认提交的时候将富文本数据双向绑定的时候,添加  .replace(/<[^>]+>/g,"")

我是保存时,那么我的代码要做如下更改,加一行this.editForm.content=this.editForm.content.replace(/<[^>]+>/g,"")

​
 SaveEditData(){
            this.editForm.content=this.editForm.content.replace(/<[^>]+>/g,"")
            Req.UpdateNews(this.editForm).then((res)=>{
                if(res.status==200)
                {
                    this.$message({type: 'success', message: '保存成功!'});
                    this.CloseWin();
                    this.GetTabData();
                }
                else{
                    this.$message({type: 'error', message: '保存失败!'});          
                }
            })
        },
​

然后在标签中就可以直接展示了:

 <el-table-column prop="contentShow" label="培训内容" show-overflow-tooltip>
                </el-table-column>

【更新】vue使用 wangeditor4 富文本 + 富文本回显带标签+wangEditor4 加字数,光标会跑到最后 问题 (已解决)

这里补充一下,还可以直接使用 v-html 具体方法,但是使用这个方法时,需要在如下场景使用里使用,直接在标签上绑定是不可以的,如:

  <el-col :span="6" class="dialog-detail-title">新闻标题:</el-col>
          <el-col :span="18" class="dialog-detail-content">{{ detailForm.title }}</el-col>
          <el-col :span="6" class="dialog-detail-title">新闻内容:</el-col>
          <el-col :span="18" class="dialog-detail-content">
               <div v-html="detailForm.content"></div>
          </el-col>
</el-col>

 【更新】vue使用 wangeditor4 富文本 + 富文本回显带标签+wangEditor4 加字数,光标会跑到最后 问题 (已解决)

wangEditor4 加字数、空格,光标会跑到最后

问题复现:

【更新】vue使用 wangeditor4 富文本 + 富文本回显带标签+wangEditor4 加字数,光标会跑到最后 问题 (已解决)

wangEditor在默认情况下,父组件给其设置内容后光标会处于首端,不符合需求。网上找的直接通过js操作的方法经过尝试没有作用(也可能是没写对),官方文档也没找到合适的方法。最终经过一番尝试后成功解决,特此记录,希望能帮到有类似需求的人。

解决:

在父组件与wangEditor通信的双向绑定数据value的watch方法中,增加一句:

this.editor.selection.moveCursor(this.editor.$textElem.elems[0],false);

 本来按照常见思路应该是放在聚焦监听函数onfocus中的,但是放在里面会报错:TypeError: Cannot read property ‘editor’ of undefined。如果放在onchange函数中倒是可以实现,不过会出现,光标先在前段显示,后跳到末尾的情况,总之放到value的watch方法中好。

watch: {
        value: function (value) {
            if (value !== this.phoneEditor.txt.html()) {
                this.phoneEditor.txt.html(this.value)    //根据父组件传来的值设置html值
            } this.phoneEditor.selection.moveCursor(this.phoneEditor.$textElem.elems[0], false);
        },                                               //value为编辑框输入的内容,这里我监听了一下值,当父组件调用得时候,如果给value赋值了,子组件将会显示父组件赋给的值},
    },

 我是直接把上面watch里面的方法改写成如上

【更新】vue使用 wangeditor4 富文本 + 富文本回显带标签+wangEditor4 加字数,光标会跑到最后 问题 (已解决)

 【更新】vue使用 wangeditor4 富文本 + 富文本回显带标签+wangEditor4 加字数,光标会跑到最后 问题 (已解决)

本文借鉴:Vue使用富文本quill-editor发送后台数据有标签问题: <p> - 简书 (jianshu.com)

wangEditor中使得光标处于文本末端的方法记录 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。