파란하늘의 지식창고
반응형

Toast UI Editor는 NHN에서 만든 오픈 소스 에디터이다.

2020년 3월 달에 2.0이 출시되었는데 jQuery 의존성이 제거되었고 Chart, Grid, Calendar 같은 유용한 기능들을 제공해준다.

https://ui.toast.com/weekly-pick/ko_20200318/

 

TOAST UI Editor 2.0 출시

TOAST UI Editor는 문서 편집을 위한 자바스크립트 라이브러리로, 마크다운(Markdown)과 위지윅(WYSIWYG) 2가지 모드의 에디터를 제공하여 사용자가 편의에 따라 자유롭게 에디터를 선택할 수 있도록 도와줍니다.

ui.toast.com

또한 jquery, react, vue에서 사용할 수 있도록 Package를 제공해주고 있어 자신의 환경에 맞게 사용할 수 있다.

https://github.com/nhn/tui.editor

 

nhn/tui.editor

🍞📝 Markdown WYSIWYG Editor. GFM Standard + Chart & UML Extensible. - nhn/tui.editor

github.com

apps 폴더 하위에 제공하는 Package가 있고 각 Package를 사용하는 가이드가 readme 문서로 제공되어 있다.

Vue에서 사용하는 방법은 /apps/vue-editor에 설명되어 있다.

https://github.com/nhn/tui.editor/tree/master/apps/vue-editor

설치

npm install --save @toast-ui/vue-editor

vue ui를 사용한다면 거기서 추가를 하면 된다.

 

사용

Editor와 Viewer를 제공해준다.

Editor는 편집을 할 수 있고 Viewer는 저장된 데이터를 화면에 출력해준다.

Editor 사용

필요한 모듈을 참조하고

import 'codemirror/lib/codemirror.css';
import '@toast-ui/editor/dist/toastui-editor.css';

import { Editor } from '@toast-ui/vue-editor';

템플릿에서 호출한다.

<template>
  <editor />
</template>

ajax로 저장하기 위해 editor의 내용을 가져와야 하는데 이를 위해 다음처럼 사용한다.

<template>
    <Editor ref="toastuiEditor" />
    <b-button @click="createAction">저장하기</b-button>
</template>

<script>
import "codemirror/lib/codemirror.css";
import "@toast-ui/editor/dist/toastui-editor.css";
import { Editor } from "@toast-ui/vue-editor";

export default {
  components: {
    Editor
  },
  methods: {
    createAction() {
      var content = this.$refs.toastuiEditor.invoke("getMarkdown");
      // content를 저장하는 액션 처리
    }
  }
};
</script>

위의 경우 markdown 형태로 가져오는 처리를 하였고

getHtml로 html 형태로 가져올 수 도 있다.

invoke가 사용하는 다양한 메서드는 api 문서를 참조하면 된다.

https://nhn.github.io/tui.editor/latest/ToastUIEditor#addHook

Viewer 사용

Editor에서 획득한 content를 어디엔가 저장하였다면 그걸 보여주는 페이지에서는 Viewer를 사용한다.

<template>
    <Viewer v-if="content != null" :initialValue="content" />
</template>

<script>
import "codemirror/lib/codemirror.css";
import "@toast-ui/editor/dist/toastui-editor.css";
import { Viewer } from "@toast-ui/vue-editor";

export default {
  components: {
    Viewer
  },
  data() {
    return {
      content : null
    }
  },
  mounted() {
  	// 어디선가 저장된 데이터를 호출
    fetch("주소").then(response => {
      if (response.ok) {
        return response.json();
      } else {
        throw response;
      }
    }).then(data => {
    	this.content = data;
    });
  }
};
</script>

initialValue는 초기에만 설정되므로 data를 ajax로 받기 전까진 Viewer가 실행되지 않도록 v-if 구문으로 체크해주어야 한다.

대부분의 내용은 Toast UI Editor 가이드 문서에 다 설명되어 있는데 Vue를 간간히 쓰는 입장에서 Viewer가 표시되지 않아 헤매었었다.

v-if로 데이터 체크하는 부분이 꼭 필요하다는 점만 신경 쓰면 사용하는데 별로 복잡한 점은 없는 듯하다.

반응형
profile

파란하늘의 지식창고

@Bluesky_

내용이 유익했다면 광고 배너를 클릭 해주세요