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

本文介绍了如何在Vue项目中使用wangeditor4.0,包括下载安装、封装组件Editor以及实现编辑器内容与Vue数据的双向绑定。通过监听组件内外变化,确保编辑器内容与父组件参数同步。

下载安装

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>
    

     

  3. 接收父组件传入的富文本内容参数
    props: {
        content: {
            type: String,
            default: ''
        }
    },
  4. 监听父组件传入参数的变化,并初始化至编辑器中
    watch: {
        content() {
            this.editor.txt.html(this.content); 
        }
    }
  5. 监听编辑器中内容的改变,并同步给父组件传入的参数
    通过onchange方法来监听编辑器中内容的变化,但是由于子组件不能直接更改父组件的内容,
    我使用$emit方式来触发父组件自定义的方法来修改数据。
    在初始化代码中添加:
    editor.config.onchange = function (newHtml) {
        if (newHtml) {
            this.$emit('update:content',newHtml);
        }
    }.bind(this)
  6. 父组件调用封装好的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 富文本编辑器,配置方便,使用简单

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值