ElEditor.vue 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <script setup lang="ts">
  2. import '@wangeditor/editor/dist/css/style.css'
  3. import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  4. import { useUserStore } from '@/stores/user'
  5. import { ACCESS_TOKEN } from '@/utils/constants'
  6. defineOptions({
  7. name: 'ElEditor'
  8. })
  9. interface Props {
  10. modelValue: string
  11. mode?: string
  12. height?: string
  13. }
  14. const props = withDefaults(defineProps<Props>(), {
  15. mode: 'simple',
  16. height: '400px'
  17. })
  18. const emits = defineEmits(['update:modelValue', 'change'])
  19. // 编辑器实例,必须用 shallowRef
  20. const editorRef = shallowRef()
  21. // 内容 HTML
  22. const valueHtml = computed({
  23. get: () => props.modelValue,
  24. set: value => emits('update:modelValue', value)
  25. })
  26. const userStore = useUserStore()
  27. const toolbarConfig = {}
  28. const editorConfig = {
  29. placeholder: '请输入内容...',
  30. MENU_CONF: {
  31. uploadImage: {
  32. server: `${import.meta.env.VITE_BASE_API}/file/upload`,
  33. headers: { [ACCESS_TOKEN]: userStore.token },
  34. fieldName: 'file',
  35. // 自定义插入图片
  36. customInsert(res: any, insertFn: Function) {
  37. const file = res?.data
  38. insertFn(import.meta.env.VITE_BASE_PATH + file)
  39. }
  40. }
  41. }
  42. }
  43. // 组件销毁时,也及时销毁编辑器
  44. onBeforeUnmount(() => {
  45. const editor = editorRef.value
  46. if (editor == null) return
  47. editor.destroy()
  48. })
  49. const handleCreated = (editor: any) => {
  50. editorRef.value = editor // 记录 editor 实例,重要!
  51. }
  52. const handleChange = (editor: any) => {
  53. emits('change', editor.getHtml())
  54. }
  55. </script>
  56. <template>
  57. <div style="border: 1px solid var(--el-border-color)" class="w-full">
  58. <Toolbar
  59. style="border-bottom: 1px solid var(--el-border-color)"
  60. :editor="editorRef"
  61. :defaultConfig="toolbarConfig"
  62. :mode="mode"
  63. />
  64. <Editor
  65. style="overflow-y: hidden"
  66. :style="{ height: height }"
  67. v-model="valueHtml"
  68. :defaultConfig="editorConfig"
  69. :mode="mode"
  70. @onCreated="handleCreated"
  71. @onChange="handleChange"
  72. />
  73. </div>
  74. </template>
  75. <style lang="scss" scoped></style>