118 lines
2.4 KiB
Vue
118 lines
2.4 KiB
Vue
<script setup>
|
|
import { uploadImagesInBatches } from '@/utils/uploadImg.ts'
|
|
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
|
|
|
|
import { onBeforeUnmount, onMounted, shallowRef } from 'vue'
|
|
import '@wangeditor/editor/dist/css/style.css'
|
|
|
|
const props = defineProps({
|
|
modelValue: {
|
|
type: Object,
|
|
required: true,
|
|
},
|
|
})
|
|
|
|
// 引入 css
|
|
|
|
const emit = defineEmits(['update:modelValue'])
|
|
|
|
const mode = 'default'
|
|
// 编辑器实例,必须用 shallowRef
|
|
const editorRef = shallowRef()
|
|
const localForm = computed({
|
|
get() {
|
|
return props.modelValue
|
|
},
|
|
set(value) {
|
|
emit('update:modelValue', value)
|
|
},
|
|
})
|
|
|
|
watch(
|
|
() => localForm.value,
|
|
(newVal) => {
|
|
emit('update:modelValue', newVal)
|
|
},
|
|
{ immediate: true, deep: true },
|
|
)
|
|
// 内容 HTML
|
|
const valueHtml = ref('')
|
|
|
|
// 模拟 ajax 异步获取内容
|
|
onMounted(() => {
|
|
// setTimeout(() => {
|
|
// valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
|
|
// }, 1500)
|
|
})
|
|
|
|
const toolbarConfig = {
|
|
|
|
}
|
|
const editorConfig = {
|
|
placeholder: '请输入内容...',
|
|
MENU_CONF: {},
|
|
}
|
|
|
|
editorConfig.MENU_CONF.uploadImage = {
|
|
// 自定义上传
|
|
async customUpload(file, insertFn) {
|
|
try {
|
|
const files = [file]
|
|
const res = await uploadImagesInBatches(files)
|
|
for (let i = 0; i < res.length; i++) {
|
|
insertFn(res[i].url)
|
|
}
|
|
}
|
|
catch (error) {
|
|
console.log('error', error)
|
|
}
|
|
},
|
|
|
|
}
|
|
|
|
// 组件销毁时,也及时销毁编辑器
|
|
onBeforeUnmount(() => {
|
|
const editor = editorRef.value
|
|
if (editor == null)
|
|
return
|
|
editor.destroy()
|
|
})
|
|
|
|
function handleCreated(editor) {
|
|
editorRef.value = editor // 记录 editor 实例,重要!
|
|
}
|
|
|
|
function handleChange(editor) {
|
|
const dom = editor.getHtml()
|
|
emit('update:modelValue', dom)
|
|
}
|
|
</script>
|
|
|
|
<template>
|
|
<div>
|
|
<client-only>
|
|
<Toolbar
|
|
style="border-bottom: 1px solid rgb(240 240 240)"
|
|
:editor="editorRef"
|
|
:default-config="toolbarConfig"
|
|
:mode="mode"
|
|
/>
|
|
<Editor
|
|
v-model="localForm"
|
|
class="editor"
|
|
style="max-height: 500px; min-height: 100px; overflow-y: auto;"
|
|
:default-config="editorConfig"
|
|
:mode="mode"
|
|
@on-created="handleCreated"
|
|
@on-change="handleChange"
|
|
/>
|
|
</client-only>
|
|
</div>
|
|
</template>
|
|
|
|
<style scoped lang='scss'>
|
|
.editor .w-e-text {
|
|
line-height: 1.2; /* 行高为字体大小的 2 倍 */
|
|
}
|
|
</style>
|