index.vue 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <template>
  2. <div ref="wrapRef" class="markdown" />
  3. </template>
  4. <script lang="ts">
  5. import {
  6. defineComponent,
  7. ref,
  8. onMounted,
  9. unref,
  10. PropType,
  11. onUnmounted,
  12. nextTick,
  13. watchEffect
  14. } from 'vue'
  15. import Vditor from 'vditor'
  16. import 'vditor/dist/index.css'
  17. export default defineComponent({
  18. props: {
  19. height: {
  20. type: Number as PropType<number>,
  21. default: 500
  22. },
  23. value: {
  24. type: String,
  25. default: ''
  26. }
  27. },
  28. emits: ['update:value'],
  29. setup(props, { attrs, emit }) {
  30. const wrapRef = ref<HTMLDivElement | null>(null)
  31. const vditorRef = ref<Vditor | null>(null)
  32. const initedRef = ref(false)
  33. function init() {
  34. const wrapEl = unref(wrapRef)
  35. if (!wrapEl) return
  36. const data = { ...attrs, ...props }
  37. vditorRef.value = new Vditor(wrapEl, {
  38. mode: 'sv',
  39. preview: {
  40. actions: []
  41. },
  42. input: (v) => {
  43. emit('update:value', v)
  44. },
  45. ...data,
  46. cache: {
  47. enable: false
  48. }
  49. })
  50. initedRef.value = true
  51. }
  52. watchEffect(() => {
  53. nextTick(() => {
  54. const vditor = unref(vditorRef)
  55. if (unref(initedRef) && props.value && vditor) {
  56. vditor.setValue(props.value)
  57. }
  58. })
  59. })
  60. onMounted(() => {
  61. nextTick(() => {
  62. init()
  63. })
  64. })
  65. onUnmounted(() => {
  66. const vditorInstance = unref(vditorRef)
  67. if (!vditorInstance) return
  68. vditorInstance.destroy()
  69. })
  70. return {
  71. wrapRef,
  72. getVditor: (): Vditor => vditorRef.value!
  73. }
  74. }
  75. })
  76. </script>