index.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <template>
  2. <div class="editor-container">
  3. <Toolbar :editor="editorRef" :mode="mode" />
  4. <Editor
  5. :mode="mode"
  6. :defaultConfig="state.editorConfig"
  7. :style="{ height }"
  8. v-model="state.editorVal"
  9. @onCreated="handleCreated"
  10. @onChange="handleChange"
  11. />
  12. </div>
  13. </template>
  14. <script setup lang="ts" name="wngEditor">
  15. // https://www.wangeditor.com/v5/for-frame.html#vue3
  16. import '@wangeditor/editor/dist/css/style.css'
  17. import { reactive, shallowRef, watch, onBeforeUnmount } from 'vue'
  18. import { IDomEditor } from '@wangeditor/editor'
  19. import { Toolbar, Editor } from '@wangeditor/editor-for-vue'
  20. // 定义父组件传过来的值
  21. const props = defineProps({
  22. // 是否禁用
  23. disable: {
  24. type: Boolean,
  25. default: () => false,
  26. },
  27. // 内容框默认 placeholder
  28. placeholder: {
  29. type: String,
  30. default: () => '请输入内容...',
  31. },
  32. // https://www.wangeditor.com/v5/getting-started.html#mode-%E6%A8%A1%E5%BC%8F
  33. // 模式,可选 <default|simple>,默认 default
  34. mode: {
  35. type: String,
  36. default: () => 'default',
  37. },
  38. // 高度
  39. height: {
  40. type: String,
  41. default: () => '310px',
  42. },
  43. // 双向绑定,用于获取 editor.getHtml()
  44. getHtml: String,
  45. // 双向绑定,用于获取 editor.getText()
  46. getText: String,
  47. })
  48. // 定义子组件向父组件传值/事件
  49. const emit = defineEmits(['update:getHtml', 'update:getText'])
  50. // 定义变量内容
  51. const editorRef = shallowRef()
  52. const state = reactive({
  53. editorConfig: {
  54. placeholder: props.placeholder,
  55. },
  56. editorVal: props.getHtml,
  57. })
  58. // 编辑器回调函数
  59. const handleCreated = (editor: IDomEditor) => {
  60. editorRef.value = editor
  61. }
  62. // 编辑器内容改变时
  63. const handleChange = (editor: IDomEditor) => {
  64. emit('update:getHtml', editor.getHtml())
  65. emit('update:getText', editor.getText())
  66. }
  67. // 页面销毁时
  68. onBeforeUnmount(() => {
  69. const editor = editorRef.value
  70. if (editor == null) return
  71. editor.destroy()
  72. })
  73. // 监听是否禁用改变
  74. watch(
  75. () => props.disable,
  76. (bool) => {
  77. const editor = editorRef.value
  78. if (editor == null) return
  79. bool ? editor.disable() : editor.enable()
  80. },
  81. {
  82. deep: true,
  83. }
  84. )
  85. // 监听双向绑定值改变,用于回显
  86. watch(
  87. () => props.getHtml,
  88. (val) => {
  89. state.editorVal = val
  90. },
  91. {
  92. deep: true,
  93. }
  94. )
  95. </script>