wwf
11 小时以前 a1d7e81859f554f3a53680cc35f0f49bf1f77098
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
<script lang="ts" setup>
import { PropType } from 'vue'
import { Editor, Toolbar } from '@wangeditor-next/editor-for-vue'
import { i18nChangeLanguage, IDomEditor, IEditorConfig } from '@wangeditor-next/editor'
import { propTypes } from '@/utils/propTypes'
import { isNumber } from '@/utils/is'
import { ElMessage } from 'element-plus'
import { useLocaleStore } from '@/store/modules/locale'
import { getRefreshToken, getTenantId } from '@/utils/auth'
import { getUploadUrl } from '@/components/UploadFile/src/useUpload'
import merge from 'lodash-es/merge'
 
defineOptions({ name: 'Editor' })
 
type InsertFnType = (url: string, alt: string, href: string) => void
 
const localeStore = useLocaleStore()
 
const currentLocale = computed(() => localeStore.getCurrentLocale)
 
i18nChangeLanguage(unref(currentLocale).lang)
 
const props = defineProps({
  editorId: propTypes.string.def('wangEditor-1'),
  height: propTypes.oneOfType([Number, String]).def('500px'),
  editorConfig: {
    type: Object as PropType<Partial<IEditorConfig>>,
    default: () => undefined
  },
  readonly: propTypes.bool.def(false),
  modelValue: propTypes.string.def(''),
  directory: propTypes.string.def('editor-default')
})
 
const emit = defineEmits(['change', 'update:modelValue'])
 
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef<IDomEditor>()
 
const valueHtml = ref('')
 
watch(
  () => props.modelValue,
  (val: string) => {
    if (!val) {
      val = ''
    }
    if (val === unref(valueHtml)) return
    valueHtml.value = val
  },
  {
    immediate: true
  }
)
 
// 监听
watch(
  () => valueHtml.value,
  (val: string) => {
    emit('update:modelValue', val)
  }
)
watch(
  () => props.readonly,
  async (val) => {
    // 特殊:等待 editorRef 渲染完成
    if (!editorRef.value) {
      await nextTick()
    }
    if (val) {
      editorRef.value?.disable()
    } else {
      editorRef.value?.enable()
    }
  }
)
 
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
}
 
// 编辑器配置
const editorConfig = computed((): IEditorConfig => {
  return merge(
    {
      placeholder: '请输入内容...',
      readOnly: props.readonly,
      customAlert: (s: string, t: string) => {
        switch (t) {
          case 'success':
            ElMessage.success(s)
            break
          case 'info':
            ElMessage.info(s)
            break
          case 'warning':
            ElMessage.warning(s)
            break
          case 'error':
            ElMessage.error(s)
            break
          default:
            ElMessage.info(s)
            break
        }
      },
      autoFocus: false,
      scroll: true,
      EXTEND_CONF: {
        mentionConfig: {
          showModal: () => {},
          hideModal: () => {}
        }
      },
      MENU_CONF: {
        ['uploadImage']: {
          server: getUploadUrl(),
          // 单个文件的最大体积限制,默认为 2M
          maxFileSize: 10 * 1024 * 1024,
          // 最多可上传几个文件,默认为 100
          maxNumberOfFiles: 100,
          // 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
          allowedFileTypes: ['image/*'],
 
          // 自定义增加 http  header
          headers: {
            Accept: '*',
            Authorization: 'Bearer ' + getRefreshToken(), // 使用 getRefreshToken() 方法,而不使用 getAccessToken() 方法的原因:Editor 无法方便的刷新访问令牌
            'tenant-id': getTenantId()
          },
 
          // 超时时间,默认为 10 秒
          timeout: 15 * 1000, // 15 秒
 
          // form-data fieldName,后端接口参数名称,默认值wangeditor-uploaded-image
          fieldName: 'file',
          // 附加参数
          meta: {
            directory: `${props.directory}-image`
          },
          metaWithUrl: false,
 
          // uppy 配置项
          uppyConfig: {
            onBeforeFileAdded: (newFile: any) => {
              newFile.id = `${newFile.id}-${Date.now()}`
              return newFile
            }
          },
 
          // 上传之前触发
          onBeforeUpload(file: File) {
            // console.log(file)
            return file
          },
          // 上传进度的回调函数
          onProgress(progress: number) {
            // progress 是 0-100 的数字
            console.log('progress', progress)
          },
          onSuccess(file: File, res: any) {
            console.log('onSuccess', file, res)
          },
          onFailed(file: File, res: any) {
            alert(res.message)
            console.log('onFailed', file, res)
          },
          onError(file: File, err: any, res: any) {
            alert(err.message)
            console.error('onError', file, err, res)
          },
          // 自定义插入图片
          customInsert(res: any, insertFn: InsertFnType) {
            insertFn(res.data, 'image', res.data)
          }
        },
        ['uploadVideo']: {
          server: getUploadUrl(),
          // 单个文件的最大体积限制,默认为 10M
          maxFileSize: 1024 * 1024 * 1024,
          // 最多可上传几个文件,默认为 100
          maxNumberOfFiles: 10,
          // 选择文件时的类型限制,默认为 ['video/*'] 。如不想限制,则设置为 []
          allowedFileTypes: ['video/*'],
 
          // 自定义增加 http  header
          headers: {
            Accept: '*',
            Authorization: 'Bearer ' + getRefreshToken(), // 使用 getRefreshToken() 方法,而不使用 getAccessToken() 方法的原因:Editor 无法方便的刷新访问令牌
            'tenant-id': getTenantId()
          },
 
          // 超时时间,默认为 30 秒
          timeout: 15 * 1000, // 15 秒
 
          // form-data fieldName,后端接口参数名称,默认值wangeditor-uploaded-image
          fieldName: 'file',
          // 附加参数
          meta: {
            directory: `${props.directory}-video`
          },
          metaWithUrl: false,
 
          // uppy 配置项
          uppyConfig: {
            onBeforeFileAdded: (newFile: any) => {
              newFile.id = `${newFile.id}-${Date.now()}`
              return newFile
            }
          },
 
          // 上传之前触发
          onBeforeUpload(file: File) {
            // console.log(file)
            return file
          },
          // 上传进度的回调函数
          onProgress(progress: number) {
            // progress 是 0-100 的数字
            console.log('progress', progress)
          },
          onSuccess(file: File, res: any) {
            console.log('onSuccess', file, res)
          },
          onFailed(file: File, res: any) {
            alert(res.message)
            console.log('onFailed', file, res)
          },
          onError(file: File, err: any, res: any) {
            alert(err.message)
            console.error('onError', file, err, res)
          },
          // 自定义插入图片
          customInsert(res: any, insertFn: InsertFnType) {
            insertFn(res.data, 'mp4', res.data)
          }
        }
      },
      uploadImgShowBase64: true
    },
    props.editorConfig || {}
  )
})
 
const editorStyle = computed(() => {
  return {
    height: isNumber(props.height) ? `${props.height}px` : props.height
  }
})
 
// 回调函数
const handleChange = (editor: IDomEditor) => {
  emit('change', editor)
}
 
// 组件销毁时,及时销毁编辑器
onBeforeUnmount(() => {
  const editor = unref(editorRef.value)
 
  // 销毁,并移除 editor
  editor?.destroy()
})
 
const getEditorRef = async (): Promise<IDomEditor> => {
  await nextTick()
  return unref(editorRef.value) as IDomEditor
}
 
defineExpose({
  getEditorRef
})
</script>
 
<template>
  <div class="border-1 border-solid border-[var(--tags-view-border-color)] z-10">
    <!-- 工具栏 -->
    <Toolbar
      :editor="editorRef"
      :editorId="editorId"
      class="border-0 b-b-1 border-solid border-[var(--tags-view-border-color)]"
    />
    <!-- 编辑器 -->
    <Editor
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :editorId="editorId"
      :style="editorStyle"
      @on-change="handleChange"
      @on-created="handleCreated"
    />
  </div>
</template>
 
<style src="@wangeditor-next/editor/dist/css/style.css"></style>