Vue.js

Vue.js 프로젝트에 텍스트 에디터 적용하기 (RichTextEditor, Vue3)

녹녹1 2024. 7. 9. 14:09

RichTextEditor 홈페이지에서 ' RichTextEditor for Vue JS examples' 다운로드

https://richtexteditor.com/download.aspx

zip 압축해제하고 index.html을 클릭해서 보면 가이드가 나와있어서 그대로 따라하면 된다.

Demo guide : 
1 - copy /richtexteditor/  to folder 'public'
2 - add 
    /richtexteditor/rte_theme_default.css
    /richtexteditor/rte.js
    /richtexteditor/plugins/all_plugins.js
      to index.html
3 - in vue component , use ref to get element , and run var rte=new RichTextEditor(div);

 

1. Vue 프로젝트의 public 폴더 안에 richtexteditor를 복사한다

2. 가이드에는 index.html에 하라고 나와있지만 우리 프로젝트의 경우에는 텍스트 에디터를 전역으로 사용할 일이 많지는 않기 때문에 그냥 RichTextEditor.vue안에서 당겨왔다.

3. Vue 컴포넌트를 만들어서 사용한다.

 

전체 코드 

자식 컴포넌트(RichTextEditor.vue) 

<script setup lang="ts">
import { onMounted, ref } from 'vue';

const richTextEditor = ref(null);
let rteInstance: any;

const loadRichTextEditor = () => {
  // CSS 파일 로드
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = '/richtexteditor/rte_theme_default.css';
  document.head.appendChild(link);

  // JS 파일 로드
  const scriptRTE = document.createElement('script');
  scriptRTE.src = '/richtexteditor/rte.js';

  const scriptPlugins = document.createElement('script');
  scriptPlugins.src = '/richtexteditor/plugins/all_plugins.js';

  scriptRTE.onload = () => {
    scriptPlugins.onload = () => {
      if (richTextEditor.value) {
        // RichTextEditor를 초기화합니다.
        rteInstance = new RichTextEditor(richTextEditor.value);
      }
    };
    document.head.appendChild(scriptPlugins);
  };

  document.head.appendChild(scriptRTE);
};

onMounted(() => {
  loadRichTextEditor();
});

const getEditorContent = () => {  
  if(rteInstance){
    console.log(rteInstance.getHTML());
    return rteInstance.getHTML(); // or rteInstance.getText() for plain text
  }
  return '';
}

defineExpose({
  getEditorContent
})
</script>

<template>
   <div ref="richTextEditor"></div>
</template>

 

부모 컴포넌트(Board.vue)

<script setup lang="ts">
import RichTextEditor from '@/components/richTextEditor/RichTextEditor.vue'
import { ref } from 'vue';

const editorRef = ref<typeof RichTextEditor>();
const test = () => {  
  editorRef.value?.getEditorContent();
}
</script>

<template>
  <RichTextEditor ref="editorRef"></RichTextEditor>
  <v-btn @click="test">
    테스트용
  </v-btn>
</template>

 

적용한 화면