index.vue 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <script setup lang="ts">
  2. import { onMounted, ref } from 'vue';
  3. import WangEditor from 'wangeditor';
  4. import { fetchUpload } from '@/service/api/common';
  5. const editor = ref<WangEditor>();
  6. const domRef = ref<HTMLElement>();
  7. const context = defineModel<string>();
  8. const props = defineProps<{
  9. height?: number;
  10. }>();
  11. const uploadConfig = {
  12. // 服务器端点
  13. server: '/smqjh-system/api/v1/files', // 请替换为你的图片上传接口
  14. // 限制大小
  15. maxSize: 5 * 1024 * 1024, // 5M
  16. // 限制类型
  17. allowedFileTypes: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'],
  18. // 超时时间
  19. timeout: 30 * 1000
  20. };
  21. function renderWangEditor() {
  22. editor.value = new WangEditor(domRef.value);
  23. setEditorConfig();
  24. configureImageUpload();
  25. editor.value.create();
  26. if (context.value) {
  27. editor.value.txt.html(context.value);
  28. }
  29. editor.value.config.onchange = (newHtml: string) => {
  30. context.value = newHtml;
  31. console.log(newHtml, 'newHtml');
  32. };
  33. }
  34. function setEditorConfig() {
  35. console.log(editor.value, 'editor.valueeditor.value');
  36. if (editor.value?.config?.zIndex) {
  37. editor.value.config.zIndex = 1000;
  38. }
  39. if (editor.value) {
  40. editor.value.config.height = props.height || 800;
  41. }
  42. // 启用粘贴文本保持格式
  43. editor.value!.config.pasteFilterStyle = true;
  44. editor.value!.config.pasteIgnoreImg = false;
  45. editor.value!.config.pasteTextHandle = (content: string) => {
  46. return content;
  47. };
  48. }
  49. function configureImageUpload() {
  50. if (!editor.value) return;
  51. // 配置图片上传参数
  52. const config = editor.value.config;
  53. // 设置图片上传配置
  54. config.uploadImgServer = uploadConfig.server;
  55. config.uploadImgMaxSize = uploadConfig.maxSize;
  56. config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
  57. config.uploadImgTimeout = uploadConfig.timeout;
  58. config.customUploadImg = async (files: File[], insertFn: (url: string) => void) => {
  59. try {
  60. const result = await fetchUpload(files[0]);
  61. const imageUrl = result.data.url;
  62. insertFn(imageUrl);
  63. } catch (error) {
  64. window.$message?.error(`上传失败${error}`);
  65. }
  66. };
  67. }
  68. onMounted(() => {
  69. renderWangEditor();
  70. });
  71. </script>
  72. <template>
  73. <div class="h-full w-full">
  74. <div ref="domRef" class="w-full bg-white dark:bg-dark"></div>
  75. </div>
  76. </template>
  77. <style scoped>
  78. :deep(.w-e-toolbar) {
  79. background: inherit !important;
  80. border-color: #999 !important;
  81. }
  82. :deep(.w-e-text-container) {
  83. background: inherit;
  84. border-color: #999 !important;
  85. }
  86. </style>