vue使用wangeditor4.0版本,并实现编辑器内容双向绑定

973 阅读1分钟

下载安装

npm i wangeditor --save

封装组件Editor

  1. 新建Vue组件Editor
  2. 初始化编辑器组件
<template lang="html">
    <div id="editor">
    </div>
</template>

<script>
    import E from 'wangeditor'
    export default {
        name: 'Editor',
        data() {
            return {
                editor: ''
            }
        },
        mounted() {
            const editor = new E("#editor");
            this.editor = editor; // 保存创建的实例
            editor.create();
        }
    }
</script>
  1. 接收父组件传入的富文本内容参数
props: {
    content: {
        type: String,
        default: ''
    }
}
  1. 监听父组件传入参数的变化,并初始化至编辑器中
watch: {
    content() {
        this.editor.txt.html(this.content); 
    }
}
  1. 监听编辑器中内容的改变,并同步给父组件传入的参数
通过onchange方法来监听编辑器中内容的变化,但是由于子组件不能直接更改父组件的内容,
我使用$emit方式来触发父组件自定义的方法来修改数据。
在初始化代码中添加:
editor.config.onchange = function (newHtml) {
    if (newHtml) {
        this.$emit('update:content',newHtml);
    }
}.bind(this)
  1. 父组件调用封装好的Editor组件
引入和注册组件不写了哈
解释一下.sync,它相当于v-on:update:content="article = $event"的简写
<Editor :content.sync="article"></Editor>

最后附上完整代码

<template lang="html">
    <div id="editor">
    </div>
</template>

<script>
    import E from 'wangeditor'
    export default {
        name: 'Editor',
        props: {
            content: {
                type: String,
                default: ''
            }
        },
        data () {
            return {
                editor: ''
            }
        },
        mounted() {
            const editor = new E("#editor");
            this.editor = editor;
            editor.config.height = 250; // 高度,单位xp
            editor.config.zIndex = 500; // z-index属性
            editor.config.onchange = function (newHtml) {// 需要改变this指向域
                if (newHtml) {
                    this.$emit('update:content',newHtml);
                }
            }.bind(this)
            editor.config.excludeMenus = [ // 配置使用哪些编辑器功能
                'emoticon',
                'video',
                'todo',
                'quote',
                'code',
                'undo',
                'redo'
            ]
            editor.create();
        },
        methods: {
        },
        watch: {
            content() {
                this.editor.txt.html(this.content);
            }
        }
    }
</script>

关于wangeditorV4版本API文档

wangEditor —— 轻量级 web 富文本编辑器,配置方便,使用简单

如果帮到您,不妨点个赞噢铁汁