index.vue 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <template>
  2. <div class="editor-wrapper">
  3. <!-- 工具栏 -->
  4. <Toolbar id="toolbar-container" :editor="editorRef" :default-config="toolbarConfig" :mode="mode" />
  5. <!-- 编辑器 -->
  6. <Editor style="height: 350px" id="editor-container" v-model="modelValue" :default-config="editorConfig" :mode="mode" @on-change="handleChange" @on-created="handleCreated" />
  7. </div>
  8. </template>
  9. <script setup>
  10. import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  11. // API 引用
  12. import { uploadFileApi } from '@/utils/file'
  13. const props = defineProps({
  14. modelValue: {
  15. type: [String],
  16. default: ''
  17. }
  18. })
  19. const emit = defineEmits(['update:modelValue'])
  20. const modelValue = useVModel(props, 'modelValue', emit)
  21. const editorRef = shallowRef() // 编辑器实例,必须用 shallowRef
  22. const mode = ref('default') // 编辑器模式
  23. const toolbarConfig = ref({}) // 工具条配置
  24. // 编辑器配置
  25. const editorConfig = ref({
  26. placeholder: '请输入内容...',
  27. MENU_CONF: {
  28. uploadImage: {
  29. // 自定义图片上传
  30. async customUpload(file, insertFn) {
  31. uploadFileApi(file).then((response) => {
  32. const { errcode, uri } = response.data
  33. const url = `${import.meta.env.VITE_APP_HOST}${uri}`
  34. if (errcode === 0) insertFn(url)
  35. })
  36. }
  37. }
  38. }
  39. })
  40. const handleCreated = (editor) => {
  41. editorRef.value = editor // 记录 editor 实例,重要!
  42. }
  43. function handleChange(editor) {
  44. modelValue.value = editor.getHtml()
  45. }
  46. // 组件销毁时,也及时销毁编辑器
  47. onBeforeUnmount(() => {
  48. const editor = editorRef.value
  49. if (editor == null) return
  50. editor.destroy()
  51. })
  52. </script>
  53. <style src="@wangeditor/editor/dist/css/style.css"></style>