본문 바로가기
Dev/실습

[Spring Boot + Vue.js] 게시판 만들기 - Toast UI Editor, Viewer

by dev_jsk 2021. 1. 14.
728x90
반응형

이번 포스팅은 게시글 작성을 위한 Toast UI Editor와 내용을 보여주는 Toast UI Viewer에 대해 알아보자

 

Toast UI Editor 컴포넌트

WYSIWYG 모드와 Markdown 모드를 지원하는 에디터 구현

 

구현

1. 의존성 설치

$ npm i @toast-ui/vue-editor

2. 컴포넌트 구현

<template>
  <div>
    <Editor
      ref="toastEditor"
      initialEditType="wysiwyg"
      height="500px"
      previewStyle="vertical"
    />
  </div>
</template>

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

export default {
  components: {
    Editor,
  },
  methods: {
    getContent() {
      return this.$refs.toastEditor.invoke('getMarkdown')
    },
    setContent(content) {
      this.$refs.toastEditor.invoke('setMarkdown', content)
    },
  },
}
</script>
  • ref 속성을 통해 Toast UI Editor 객체에 접근하여 다양한 함수를 사용 가능하다.
  • invoke('함수명') 을 통해 해당 객체의 함수를 사용할 수 있다.
  • getContent() 는 에디터에 작성된 내용을 리턴하는 함수로 상위 컴포넌트에서 쉽게 접근하기 위해 구현한 함수이다.
  • setContent() 는 에디터에 인수로 받은 값을 설정하는 함수로 상위 컴포넌트에서 쉽게 접근하기 위해 구현한 함수이다.

사용 방법

게시판 작성 컴포넌트에서 에디터 컴포넌트를 import 하여 사용한다.

<template>
  <Editor ref="editor" />
</template>

<script>
import Editor from '@/components/common/Editor'

export default {
  components: {
    Editor,
  },
  methods: {
    async save() {
      var content = this.$refs.editor.getContent()
    },
  },
}
</script>
  • ref 속성을 통해 Editor 컴포넌트의 getContent() 함수에 접근할 수 있다.

동작 확인

Toast UI Viewer 컴포넌트

게시글 내용을 보여주기 위한 컴포넌트이다.

 

구현

<template>
  <div>
    <Viewer ref="toastViewer" height="500px" />
  </div>
</template>

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

export default {
  components: {
    Viewer,
  },
  methods: {
    setContent(content) {
      this.$refs.toastViewer.invoke('setMarkdown', content)
    },
  },
}
</script>
  • Editor 컴포넌트와 동일하게 ref 속성을 통해 Toast UI Viewer 객체에 접근하여 다양한 함수를 사용할 수 있다.
  • setContent() 는 에디터에 인수로 받은 값을 설정하는 함수로 상위 컴포넌트에서 쉽게 접근하기 위해 구현한 함수이다.

사용 방법

게시글 상세 컴포넌트에서 뷰어 컴포넌트를 import 하여 사용한다.

<template>
  <div style="height:300px;">
    <Viewer ref="viewer" /><br />
  </div>
</template>

<script>
import Viewer from '@/components/common/Viewer'
import { getBoardDetailAPI } from '@/api/index'

export default {
  components: {
    Viewer,
  },
  mounted() {
    getBoardDetailAPI({
      params: {
        docNo: this.$route.query.docNo,
      },
    })
      .then(response => {
        this.$refs.viewer.setContent(response.data.content)
      })
      .catch(error => {
        console.log(error)
      })
  },
}
</script>
  • API를 통해 해당 게시글 내용을 받아 Viewer 컴포넌트에 내용을 설정한다.

동작 확인

 

728x90
반응형

댓글