seatonwan9
2025-08-14 a0fc5b1e703769a8936fd8671ec9cdd9adfda20a
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
<template>
  <div class="border-1 border-solid border-[var(--el-border-color)] z-99">
    <!-- 工具栏 -->
    <Toolbar
        :editor="editorRef"
        :editorId="editorId"
        class="border-0 b-b-1 border-solid border-[var(--el-border-color)]"
    />
    <!-- 编辑器 -->
    <Editor
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :editorId="editorId"
        :style="editorStyle"
        @on-change="handleChange"
        @on-created="handleCreated"
    />
  </div>
  <Dialog v-model="dialogVisible" title="上传文件">
    <el-upload
        ref="uploadRef"
        v-model:file-list="fileList"
        :action="url"
        :auto-upload="false"
        :data="data"
        :disabled="formLoading"
        :headers="uploadHeaders"
        :limit="1"
        :on-success="submitFormSuccess"
        accept=""
        drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text"> 将文件拖到此处,或 <em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip" style="color: red">
          <!-- 提示:仅允许导入 jpg、png、gif 格式文件! -->
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitFileForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
 
<script lang="ts" setup>
import {PropType} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {i18nChangeLanguage, IDomEditor, IEditorConfig} from '@wangeditor/editor'
import {propTypes} from '@/utils/propTypes'
import {isNumber} from '@/utils/is'
import {ElMessage} from 'element-plus'
import {useLocaleStore} from '@/store/modules/locale'
import {getAccessToken, getTenantId} from '@/utils/auth'
 
defineOptions({name: 'Editor'})
 
const message = useMessage() // 消息弹窗
 
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const url = import.meta.env.VITE_UPLOAD_URL
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const data = ref({path: ''})
const uploadRef = ref()
 
type InsertFnType = (url: string, alt: string, href: string) => void
type InsertFnType1 = (url: string, poster: string) => void
const localeStore = useLocaleStore()
 
const InsertFnInfo = ref()
 
const currentLocale = computed(() => localeStore.getCurrentLocale)
 
i18nChangeLanguage(unref(currentLocale).lang)
 
const props = defineProps({
  editorId: propTypes.string.def('wangeEditor-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('')
})
 
const emit = defineEmits(['change', 'update:modelValue'])
 
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef<IDomEditor>()
 
const valueHtml = ref('')
 
/** 提交表单 */
const submitFileForm = () => {
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  unref(uploadRef)?.submit()
}
 
const submitFormSuccess = (d) => {
  InsertFnInfo.value(d.data, 'image')
  // 清理
  dialogVisible.value = false
  formLoading.value = false
  unref(uploadRef)?.clearFiles()
}
 
watch(
    () => props.modelValue,
    (val: string) => {
      if (val === unref(valueHtml)) return
      valueHtml.value = val
    },
    {
      immediate: true
    }
)
 
// 监听
watch(
    () => valueHtml.value,
    (val: string) => {
      emit('update:modelValue', val)
    }
)
 
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
}
 
// 编辑器配置
const editorConfig = computed((): IEditorConfig => {
  return Object.assign(
      {
        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,
        MENU_CONF: {
          ['uploadImage']: {
            customBrowseAndUpload(insertFn: InsertFnType) {
              dialogVisible.value = true
              InsertFnInfo.value = insertFn
            },
            // 自定义插入图片
            customInsert(res: any, insertFn: InsertFnType) {
              insertFn(res.data, 'image', res.data)
            }
          },
          ['uploadVideo']: {
            customBrowseAndUpload(insertFn: InsertFnType1) {
              dialogVisible.value = true
              InsertFnInfo.value = insertFn
            },
            // 自定义插入图片
            customInsert(res: any, insertFn: InsertFnType1) {
              insertFn(res.data, 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>
 
<style src="@wangeditor/editor/dist/css/style.css"></style>