Published 2023. 11. 8. 14:45

tui-editor는 공식적으로 vue2만 지원을 해서 vue3로 된 자료 찾다가 아래 소스를 찾아서 적용해 보았다.

<template>
    <div class="toast-edit" ref="tuiEditor"></div>

</template>

<script>
import "prismjs/themes/prism.css";
import "@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight.css";
import "tui-color-picker/dist/tui-color-picker.css";
import "@toast-ui/editor-plugin-color-syntax/dist/toastui-editor-plugin-color-syntax.css";
import '@toast-ui/editor/dist/toastui-editor.css'; // Editor's Style
import '@toast-ui/editor/dist/toastui-editor-viewer.css';

import colorSyntax from "@toast-ui/editor-plugin-color-syntax";
import Prism from "prismjs";
import "prismjs/components/prism-c";
import "prismjs/components/prism-cpp";
import "prismjs/components/prism-java";
import "prismjs/components/prism-python";
import "@toast-ui/editor/dist/i18n/ko-kr";
import Editor from "@toast-ui/editor";
import codeSyntaxHighlight from "@toast-ui/editor-plugin-code-syntax-highlight";

let editor = null
// import api from "../api";
export default {
    name: "ToastEdtior",
    components: {
    },
    props: {
        data: {
            type: String,
            default: "",
        },

    },
    data() {
        return {
            changedPrism: null,
            // editor: null,

        };
    },
    mounted() {
        this.changedPrism = Prism;

        this.setEditor();
        if (this.data) {
            try {
                editor.setMarkdown(this.data);
            } catch (e) {
                editor.setHTML(this.data);
            }
        }
    },
    methods: {
        setEditor(data) {
            editor = new Editor({
                el: this.$refs.tuiEditor,
                plugins: [
                    colorSyntax,
                    [codeSyntaxHighlight, { highlighter: this.changedPrism }],
                ],
                initialEditType: "wysiwyg",
                language: "ko",
                events: {
                    change: this.onChangeEditor,
                },
                // hooks: {
                    // addImageBlobHook: this.addImageBlobHook,
                // },
            });
        },

        // async addImageBlobHook(file, setText, type) {
        //     try {
        //         if (!file) return false;
        //
        //         // 이미지 제외 막기 처리하기
        //         if (file && file.size > 5242880) {
        //             const size = (file.size / (1000 * 1000)).toFixed(1);
        //             alert(
        //                 `최대 업로드 사이즈(5 MB)를 초과 하였습니다.\n현재 사이즈 ${size}MB`
        //             );
        //
        //             return false;
        //         }
        //         // api 업로드 만들기
        //         const formData = new FormData();
        //         formData.append("image", file);
        //         const { data } = await api.uploadImageFile(formData);
        //         if (data.success === true) {
        //             setText(data.file_path, "image");
        //         }
        //
        //         //
        //     } catch (e) {
        //         alert("파일 업로드에 실패하였습니다");
        //     }
        // },

        onChangeEditor() {
            this.editorText = editor.getMarkdown();

        },
    },
    watch: {
        // watch를 활용한 props 변경 감지
        data(newValue) {
            if (this.editorText !== newValue) {
                editor.setMarkdown(newValue);
            }
        },

        editorText(newValue, oldValue) {
            if (newValue !== oldValue) {
                this.$emit("setContent", editor.getMarkdown());
            }
        },
    },
};
</script>

<style>

</style>

개발 하신분은 data에 editor를 선언하고, 필요 할때 this.editor로 호출하게 개발을 하셨는데, 해당 소스를 가져와서 적용해보니 아래와 같은 오류가 났다. 그래서 이렇게 저렇게 테스트 해보다 editor객체를 멤버 변수로 빼서 테스트를 해보니 오류 없이 정상적으로 작동이 되었다.

아래와 같은 오류가 나오는 이유는 모르겠지만, 에디터에 값을 넣을때 오류가 난다. setHTML뿐 아니라, setMarkdown을 해도 동일한 오류가 난다. 

index.js:833 Uncaught (in promise) RangeError: Applying a mismatched transaction
    at _EditorState.applyInner (index.js:833:19)
    at _EditorState.applyTransaction (index.js:797:45)
    at EditorView.dispatchTransaction (index.js:19588:46)
    at EditorView.dispatch (index.js:5506:33)
    at WysiwygEditor2.setModel (index.js:19676:19)
    at ToastUIEditorCore2.setHTML (index.js:22566:27)
    at Proxy.mounted (ToastEdtior.vue:51:29)
    at vue.runtime.esm-bundler.js:4625:88
    at callWithErrorHandling (vue.runtime.esm-bundler.js:1575:18)
    at callWithAsyncErrorHandling (vue.runtime.esm-bundler.js:1583:17)​

 

원본 출처: https://loy124.tistory.com/393

 

vue Toast UI Editor 적용기

사내 프로젝트를 하던 도중 기존에 사용하던 에디터가 너무 오래되어 교체를 할 필요성이 생겨 에디터를 새로 적용하기로 하였고 고민하던 도중 nhn에서 운영하는 오픈소스인 Toast Ui를 활용하기

loy124.tistory.com

 

복사했습니다!