index.vue 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <template>
  2. <div class="markdown" ref="wrapRef" />
  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. emits: ['update:value'],
  19. props: {
  20. height: {
  21. type: Number as PropType<number>,
  22. default: 360,
  23. },
  24. value: {
  25. type: String,
  26. default: '',
  27. },
  28. },
  29. setup(props, { attrs, emit }) {
  30. const wrapRef = ref<Nullable<HTMLDivElement>>(null);
  31. const vditorRef = ref<Nullable<Vditor>>(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>