zhuoyuan.wang
2024-06-19 15ebe96f28cadec6a726c5324593a40bbf56205f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<template>
  <div class="app-wang-editor" v-loading="loading">
    <Toolbar
      class="toolbar"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      mode="default"
    />
    <Editor
      :style="`height: ${height}px;`"
      class="editor"
      v-model="htmlValue"
      :defaultConfig="editorConfig"
      mode="default"
      @onCreated="handleCreated"
    />
    <input type="file" accept="image/*" name="fileToUpload" id="fileId" @change="onFileChange" style="display:none;">
  </div>
</template>
 
<script setup>
 
import '@wangeditor/editor/dist/css/style.css';
 
import {Editor, Toolbar} from '@wangeditor/editor-for-vue';
 
import * as api from '@/api';
import {useEntityStore} from "@/store/modules";
 
const props = defineProps({
  complementHeight: {
    type: Number,
    default: 0
  },
});
 
const loading = ref(false);
 
const height = computed(() => window.innerHeight - 332 - props.complementHeight);
 
const entityStore = useEntityStore();
 
/**
 * 编辑器实例,必须用 shallowRef
 * @type {ShallowRef<any>}
 */
const editorRef = shallowRef()
 
const htmlValue = ref('');
 
const toolbarConfig = {
  excludeKeys: ['emotion', 'group-video']
}
 
let insertFn;
 
const editorConfig = {
  MENU_CONF: {
    uploadImage: {
      /**
       * 自定义选择图片
       * @param _insertFn
       */
      customBrowseAndUpload(_insertFn) {
        insertFn = _insertFn;
        document.getElementById("fileId").click();
      }
    }
  },
  placeholder: '请输入内容...'
};
 
const onFileChange = async ({target}) => {
  loading.value = true;
  const formData = new FormData();
  formData.append('file', target.files[0]);
  const ids = await api.file.uploadFile(formData);
  const path = await api.file.downloadFile(ids[0]);
  insertFn(path, target.files[0].name, path);
  loading.value = false;
}
 
/**
 * 组件销毁时,也及时销毁编辑器
 */
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return
  editor.destroy();
});
 
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例,重要!
}
 
const getValue = () => {
 return  htmlValue.value;
}
 
const init = ({value}) => {
  htmlValue.value = value;
}
 
defineExpose({
  /**
   * 初始化
   */
  init,
  getValue
});
 
</script>
 
<style lang="scss">
.app-wang-editor {
  border: 1px solid #ccc;
 
  .toolbar {
    border-bottom: 1px solid #ccc;
  }
 
  .editor {
    overflow-y: hidden;
    height: 500px;
  }
}
</style>