<template>
<div class="wang-editor">
<Toolbar
style="border-bottom: 1px solid #ccc"
:editor="editorRef"
:defaultConfig="toolbarConfig"
:mode="mode"
/>
<Editor
:style="{'height': editHeight+'px', 'overflowY': 'hidden'}"
v-model="valueHtml"
:defaultConfig="editorConfig"
:mode="mode"
@onCreated="handleCreated"
@onChange="handleChange"
/>
</div>
</template>
<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, shallowRef, watch, ref } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import {uploadFile} from "@/api/project";
import { ElMessage } from "element-plus";
const props = withDefaults(
defineProps<{
desc: string; //富文本默认值
editHeight?: number;
}>(),
{
desc:'',
editHeight: 300
}
)
const emit = defineEmits(['setDesc'])
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref('')
let oldVal = ""
const toolbarConfig = {
excludeKeys: ["insertImage", "group-video"] //去掉网络上传图片和上传视频
}
const mode = shallowRef('default') //mode="default" / simple
const editorConfig = {
placeholder: '请输入内容...',
MENU_CONF:{
uploadImage:{
// 自定义上传
customUpload: upfile
},
}
}
watch(() => props.desc,
(val: string) => {
valueHtml.value = val
oldVal = val
},{immediate: true, deep:true})
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value
if (editor == null) return
editor.destroy()
})
const handleCreated = (editor:any) => {
valueHtml.value = ""
editorRef.value = editor // 记录 editor 实例
// 初始化富文本框数据会回显失败,这一句很重要
setTimeout(() => {
valueHtml.value = oldVal
},0)
}
//富文本框值改变,触发回调
const handleChange = () => {
emit('setDesc', valueHtml.value)
}
//上传图片
async function upfile(file:any, insertFn:any){
var form_data = new FormData()
form_data.append("type", 'other')
form_data.append("file", file)
const res = await uploadFile(form_data);
if(res?.code === 200 ){
//图片上传成功之后回显
insertFn(res.url, 'image', res.url)
}else{
ElMessage({
message: res?.msg || "上传文件失败",//+res?.msg,
type: 'error',
})
}
}
</script>
<style lang="less" scoped>
.wang-editor{
border: 1px solid rgba(0, 0, 0, 0.15);
width: 100%;
}
</style>
注意:引用该组件需添加唯一key
<WangEditor :desc="ruleForm.description" :edit-height="200" @setDesc="setDesc" :key="wangEditorId"/>