vue3 markdown 编辑器的使用与封装

890 阅读1分钟

tui.editor(TOAST UI Editor)是一款所见即所得的Markdown编辑器。TOAST UI Editor提供Markdown模式和WYSIWYG模式。它的功能非常强大,你可以编辑表格,UML图和图表等。 tui-editor官方地址

npm i @toast-ui/editor@3.0.2 --save
<template>
  <div class="markdown-container">
    <div id="markdown-box" />
  </div>
</template>

<script setup>
import MKEditor from '@toast-ui/editor'
import '@toast-ui/editor/dist/toastui-editor.css'
import { defineProps, onMounted, watch, defineExpose } from 'vue'

const store = useStore()
const props = defineProps({
  content: { type: String, default: '' }
})

// editor 实例
let mkEditor
let el

onMounted(() => {
  el = document.querySelector('#markdown-box')
  initMkeditor()
})

const initMkeditor = () => {
  mkEditor = new MKEditor({
    el,
    height: `${props.height}px`,
    previewStyle: 'vertical',
    language: 'zh-CN'
  })

  // 数据回显
  if (props.content) {
    mkEditor.setHTML(props.content)
  }
}

const getContent = () => {
  return mkEditor.getHTML()
}

defineExpose({ getContent })

</script>
<template>
  <markdown ref="markdownRef" :content="content" />
</template>

<script setup>
import { ref } from 'vue'
import Markdown from '@/components/Markdown/index'

const content = ref('')
const markdownRef = ref(null)

const currentContent = markdownRef.value.getContent()
</script>