动态

详情 返回 返回

vue使用wangeditor4.0版本,並實現編輯器內容雙向綁定 - 动态 详情

下載安裝

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 富文本編輯器,配置方便,使用簡單

如果幫到您,不妨點個贊噢鐵汁

Add a new 评论

Some HTML is okay.