index.vue 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <template>
  2. <div class="m-wangEditor">
  3. <Toolbar
  4. style="border-bottom: 1px solid #ccc"
  5. :editor="editorRef"
  6. :default-config="toolbarConfig"
  7. :mode="mode"
  8. />
  9. <Editor
  10. v-model="valueHtml"
  11. class="editor-content'"
  12. style="height: 300px; overflow-y: hidden"
  13. :default-config="editorConfig"
  14. :mode="mode"
  15. @on-created="handleCreated"
  16. />
  17. </div>
  18. </template>
  19. <script lang="ts" setup>
  20. // 引入 wangEditor
  21. import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  22. import '@wangeditor/editor/dist/css/style.css' // 引入 css
  23. import { onBeforeUnmount, onMounted, watch, shallowRef, ref, computed } from 'vue'
  24. let editors = null
  25. // 编辑器实例,必须用 shallowRef
  26. const editorRef = shallowRef()
  27. const toolbarConfig = {}
  28. const editorConfig = { placeholder: '请输入内容...' }
  29. // 内容 HTML
  30. const mode = ref('default')
  31. let emit = defineEmits(['update:modelValue'])
  32. let props = defineProps({
  33. modelValue: String,
  34. })
  35. const getEditorData = () => {
  36. // 通过代码获取编辑器内容
  37. let data = editors.txt.html()
  38. alert(data)
  39. }
  40. const handleCreated = (editor) => {
  41. editorRef.value = editor // 记录 editor 实例,重要!
  42. }
  43. const valueHtml = computed({
  44. get() {
  45. return props.modelValue
  46. },
  47. set(val) {
  48. // 防止富文本内容为空时,校验失败
  49. if (editorRef.value.isEmpty()) val = ''
  50. emit('update:modelValue', val)
  51. },
  52. })
  53. // 组件销毁时,也及时销毁编辑器
  54. onBeforeUnmount(() => {
  55. // 调用销毁 API 对当前编辑器实例进行销毁
  56. const editor = editorRef.value
  57. if (editor == null) {
  58. return
  59. }
  60. editor.destroy()
  61. })
  62. </script>
  63. <style lang="scss" scoped>
  64. .m-wangEditor {
  65. z-index: 99;
  66. width: 100%;
  67. border: 1px solid #cccccc;
  68. .editor-toolbar {
  69. border-bottom: 1px solid #cccccc;
  70. }
  71. .editor-content {
  72. overflow-y: hidden;
  73. }
  74. }
  75. </style>