<!--
 * @FileDescription: 富文本编辑器 wangEditor5 https://github.com/wangeditor-team/wangEditor
 * @Date: 2023-10-16
 * @LastEditTime: 2023-10-16
-->
<script setup lang="ts">
import { onMounted, ref, shallowRef, onBeforeUnmount } from 'vue';
import { createEditor, createToolbar } from '@wangeditor/editor';

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const viewHtml = ref('');

onMounted(() => {
    initEditer();
})
onBeforeUnmount(() => {
    // 组件销毁时，也及时销毁编辑器
    const editor = editorRef.value
    if (editor == null) return;
    editor.destroy();
})

function initEditer() {
    // editor
    const editorConfig = {
        placeholder: '请输入内容...',
    };
    const editor = createEditor({
        selector: '#editor-container',
        html: '<p><br></p>',
        config: editorConfig,
        mode: 'simple', // 'default' or 'simple'
    });
    // 记录 editor 实例
    editorRef.value = editor;
    //
    // toolbar
    const toolbarConfig = {};
    createToolbar({
        editor,
        selector: '#toolbar-container',
        config: toolbarConfig,
        mode: 'simple', //  'default' or 'simple'
    })
}

//  获取 HTML 内容
function getHtml() {
    const editor = editorRef.value;
    const html = editor.getHtml();
    viewHtml.value = html;
    console.log('html=', html);
}
//  获取纯文本内容
function getText() {
    const editor = editorRef.value;
    const text = editor.getText();
    console.log('text=', text);
}

</script>
<template>
    <div>
        <div>快速开始：https://www.wangeditor.com/v5/getting-started.html</div>
        <div>
            <button @click="getHtml">getHtml</button>
            <button @click="getText">getText</button>
        </div>

        <div class="q-pa-md">
            <div id="editor-wrapper">
                <div id="toolbar-container"><!-- 工具栏 --></div>
                <div id="editor-container"><!-- 编辑器 --></div>
            </div>
        </div>
        <div class="q-pa-md">
            <div class="view-box editor-content-view">
                <div v-html="viewHtml"></div>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
#editor-wrapper {
    border: 1px solid $border-color;
    z-index: 100;
    /* 按需定义 */
}

#toolbar-container {
    border-bottom: 1px solid $border-color;
    display: flex;
    flex-direction: row;
}

#editor-container {
    height: 500px;
    background-color: pink;
}

.view-box {
    overflow: auto;
    border: 1px solid $border-color;
    height: 400px;
}
</style>
