vue2使用富文本wangeditor

安装

npm i wangeditor --save

引用

import E from 'wangeditor';

使用

        // 富文本初始化
        initEditor() {
            this.isEdit = true;
            this.$nextTick(() => {
                this.editor = new E(this.$refs.editorElem); //绑定节点
                this.editor.config.height = 550; //默认高度为 300,设置高度时不需要添加单位
                this.editor.config.zIndex = 100;
                this.editor.config.placeholder = ''; //当设置为空时,可以清除提示文字
                this.editor.config.focus = false; //可以取消自动聚焦
                this.editor.config.showLinkImg = false;
                this.editor.config.filterJs = false;
                this.editor.config.uploadImgMaxLength = 1;
                this.editor.config.uploadImgMaxSize = 2 * 1024 * 1024; // 2M
                this.editor.config.customUploadImg = async file => {
                    console.log(file[0]);
                    const reader = new FileReader();
                    reader.readAsDataURL(file[0]);
                    const formData = new FormData();
                    formData.append('file', file[0]);
                    formData.append('module', 'proposal');
                    const { data } = await Upload(formData);
                    if (data.code === 200) {
                        console.log(data.data.fullPath);
                        this.editor.cmd.do(
                            'insertHTML',
                            `
{ if (this.editor == null) { this.editor.create(); this.editor.txt.html(''); } else { this.editor.destroy(); //判断编辑器是否被创建,如果创建了就先销毁。 this.editor.create(); this.$nextTick(() => { let content = ''; this.chapterList.chapterContent.forEach(item => { if (item.content) { content += item.content .replace(/\n\n\n/g, '
       ') .replace(/\n\n/g, '
       '); content = content.replace(/\n/g, `
       `); } // 图片回显 if (item.image.path) { content += `
图${this.chapterList.chapterIndex}-${item.image.index} ${item.image.title}

       `; } // 表格回显 if (item.table.title) { content += `
表${this.chapterList.chapterIndex}-${item.table.index} ${item.table.title}`; item.table.head.forEach(item => { content += ``; }); content += ``; item.table.content.forEach(item => { content += ``; item.forEach(item => { content += ``; }); content += ``; }); content += `
${item}
${item}
`; } }); content = `
${content .replace(`
       `, ``) .replace(new RegExp('°E。'), `°E。
       `)}
`; this.editor.txt.html(content); }); } }); }); },

在data(){}中定义editor:

export default {
    data() {
        return {
            editor: null,
        };
    },

然后根据需求调用就好了,

this.$nextTick(()=>{})中处理的数据是因为后端返回来的数据结构是数组,遍历赋值标签转字符串的处理操作,如果后端返回来的是字符串直接赋值就好了。

注意:

要使用this.$nextTick(()=>{}),有时候会有渲染不上报错的问题。

你可能感兴趣的:(html)