美文网首页
wangeditor入门

wangeditor入门

作者: 秀萝卜 | 来源:发表于2021-09-14 11:33 被阅读0次

1.引入wangeditor

  "dependencies": {
    "wangeditor": "^4.2.2"
  },

2.页面使用wangeditor

<el-form-item label="帮助内容" prop="content">
    <editor-bar :content="ruleForm.content" :determine="determine" @change="changeEditor"></editor-bar>
</el-form-item>

determine: 0, // 是否是编辑功能  这里是用来干嘛的呢?判断是否是编辑,如果是那么删除不用的图片。
// 获取富文本里面的内容
changeEditor(e){
    this.ruleForm.context = e;
},

import EditorBar from '../components/wangeditor'; // wangEditor富文本
components: {
   EditorBar, // 富文本
 }

3.封装的组件

<style lang="scss">
    .editor-exam {
        width: 100%;
        margin: 0;
        .toolbar {
            border: 1px solid #ccc;
        }
        .text {
            border: 1px solid #ccc;
            height: 500px!important;
        }
        // 内容块
        .w-e-text-container{
            height: 495px;
        }
    }
</style>
<template lang="html">
    <div class="editor-exam">
        <!-- 工具标签 -->
        <div ref="toolbar" class="toolbar"></div>
        <!-- 编辑框 -->
        <div ref="editorBig" class="text"></div>
    </div>
</template>

<script>
import E from 'wangeditor'; // 引入富文本编辑器
import { home } from '../../api/index';
import { client } from '../../common/js/oss'; // 阿里云oss秘钥
export default {
    name: 'Editorbar',
    data() {
        return {
            editor: null, // 富文本框
            info_: null, // 富文本内容
            allImg: [], // 所有img数据
        }
    },
    // 父级传过来参数
    props: {
        content: {
            type: String,
            default: '',
        },
        determine:{
            type: Number
        }
    },
    // 检查数据变化
    watch: {
        determine: function(a,b){     //a是value的新值,b是旧值
            console.log(a)
            if(a == 1){
                let self = this;
                let lastImg = this.getSrc(this.info_);
                console.log(lastImg)
                console.log(self.allImg)
                let diff = self.allImg.filter(function (val) { return lastImg.indexOf(val) == -1 });
                if(diff.length>0){
                    home.getStsMessage().then((response) => {
                        if (response.status == 200) {
                            for(let i=0;i<diff.length;i++){
                                client(response.data).delete(diff[i]);
                            }
                        } else {
                            this.$message({
                                showClose: true,
                                message: data.msg,
                                type: 'error'
                            });
                        }
                    }).catch((err) => {
                        console.log(err);
                    })
                }
            }
        },
    },
    // 方法
    methods: {
        // 初始化 富文本
        seteditor() {
            this.editor = new E(this.$refs.toolbar, this.$refs.editorBig);
            // 内容变化时
            this.editor.config.onchange = (html) => {
                this.info_ = html // 绑定当前逐渐地值
                this.$emit('change', this.info_) // 将内容同步到父组件中
                // 有图片变化时 -- 进行
                this.uploaderImg();
            }
            // 配置菜单
            this.editor.config.menus = [
                'head', // 标题
                'bold', // 粗体
                'fontSize', // 字号
                'fontName', // 字体
                'italic', // 斜体
                'underline', // 下划线
                'strikeThrough', // 删除线
                'indent', // 缩进
                'lineHeight', // 行高
                'foreColor', // 文字颜色
                'backColor', // 背景颜色
                'link', // 插入链接
                'list', // 列表
                'justify', // 对齐方式
                'quote', // 引用
                'emoticon', // 表情
                'image', // 插入图片
                'table', // 表格
                //'video', // 插入视频
                'code', // 插入代码
                'undo', // 撤销
                'redo', // 重复
            ]
            this.editor.config.lineHeights = ['1', '1.5', '1.7', '2', '2.5', '3'];
            // 创建富文本编辑器
            this.editor.create()
        },
        // 图片上传 -- 阿里云
        uploaderImg(){
            let that = this;
            // 配置 server 接口地址
            this.editor.config.uploadImgServer = '/hswebimg.oss-cn-beijing-internal.aliyuncs.com';
            // 自定义 -- 上传图片
            this.editor.config.customUploadImg = function (resultFiles, insertImgFn) {
                // resultFiles 是 input 中选中的文件列表
                // insertImgFn 是获取图片 url 后,插入到编辑器的方法
                home.getStsMessage().then((response) => {
                    if (response.status == 200) {
                        let files = resultFiles[0],
                        point = files.name.lastIndexOf('.'),
                        suffix = files.name.substr(point),
                        fileName = files.name.substr(0, point),
                        date = Date.parse(new Date()),
                        fileNames = `${fileName}_${date}${suffix}`;
                        client(response.data).multipartUpload('richTextImg/'+fileNames, files).then(res => {
                            that.allImg.push('richTextImg/'+fileNames);
                            let fileUrl = res.url ? res.url : 'http://'+ res.bucket + '.oss-cn-beijing.aliyuncs.com/' + res.name;
                            // 把图片地址赋值给 富文本
                            insertImgFn(fileUrl);
                        }).catch(err => {
                            that.$message.error('上传失败');
                            console.log(err)
                        })
                    } else {
                        this.$message({
                            showClose: true,
                            message: data.msg,
                            type: 'error'
                        });
                    }
                }).catch((err) => {
                    console.log(err);
                })
            }
        },
        /**
        * 取出区域内所有img的src
        */
        getSrc (html) {
            var imgReg = /<img.*?(?:>|\/>)/gi
            // 匹配src属性
            var srcReg = /src=[\\"]?([^\\"]*)[\\"]?/i
            var arr = html.match(imgReg);
            let imgs = []; // 存储的图片名称
            if (arr) {
                for (let i = 0; i < arr.length; i++) {
                    var src = arr[i].match(srcReg)[1];
                    let  point = src.lastIndexOf('.');
                    let  substr2 = src.lastIndexOf('/');
                    let  fileName = src.substr(substr2+1, point);
                    imgs.push("richTextImg/"+fileName)
                }
            }
            return imgs;
        },
    },
    //生命周期 - 挂载完成(访问DOM元素)
    mounted() {
        // 初始化 富文本
        this.seteditor();
        // 内容回显
        this.editor.txt.html(this.content);
        this.allImg = this.getSrc(this.content);
        console.log(this.allImg)
    },
}
</script>



相关文章

网友评论

      本文标题:wangeditor入门

      本文链接:https://www.haomeiwen.com/subject/dclcgltx.html