直接上代码
富文本编辑器版本:
"vue": "^3.0.5",
"@wangeditor/editor": "^5.1.7",
"@wangeditor/editor-for-vue": "^5.1.12",
组件具体封装如下:
<template>
<div class="editorPage">
<Toolbar mode="simple"
class="toolBar"
:defaultConfig="toolbarConfig"
:editor="editorRef" />
<Editor class="editorBody"
v-model="content"
:defaultConfig="editorConfig"
@onCreated="handleCreated"
@onChange="handleChange"
mode="simple" />
</div>
</template>
<script>
import { toRefs, onMounted, reactive, onBeforeUnmount, shallowRef } from "vue"
import { fileUpload } from "@/services"
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import "@wangeditor/editor/dist/css/style.css"
export default {
name: "editorPage",
components: { Editor, Toolbar },
setup(props, context) {
const allData = reactive({
content: '',
MENU_CONF: {},
toolbarConfig: {
// 显示操作菜单
toolbarKeys: ['headerSelect', 'underline', 'italic', 'bold', 'fontSize', 'color', 'fontFamily',
"uploadImage", 'justifyLeft', 'justifyRight', 'justifyCenter',
],
},
editorConfig: {
placeholder: '请输入内容...',
MENU_CONF: {},
},
})
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef()
const handleCreated = (editor) => {
editorRef.value = editor; // 记录 editor 实例,重要!
}
// 富文本上传图片
allData.editorConfig.MENU_CONF["uploadImage"] = {
// 自定义上传图片方法
async customUpload(file, insertFn) {
let formdata = new FormData();
formdata.append("files", file);
let config = {
headers: { "Content-Type": "multipart/form-data" },
};
let res = await fileUpload(formdata, config);
if (res && res.code === 200) {
// 富文本中插入图片
insertFn(res.data[0].fileCloudStorageKey);
}
}
}
// 向父组件传值
const handleChange = (editor) => {
context.emit("editorContent", allData.content);
}
onMounted(() => {
})
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const { value } = editorRef
if (value === null) return
value.destroy()
})
return {
...toRefs(allData),
handleCreated,
editorRef,
handleChange,
}
}
}
</script>
<style lang="less">
.editorPage {
width: 640px;
.toolBar {
border-bottom: 1px solid #ccc;
color: #fff;
.w-e-bar,
.w-e-bar-divider {
background: #1b4253;
}
.w-e-bar svg,
.w-e-bar-item button {
fill: #999;
color: #999;
}
}
.editorBody {
height: 305px !important;
width: 100%;
overflow-y: hidden;
.w-e-text-container {
background: #1b4253;
color: #01cac0;
}
}
}
</style>
父组件引用时:
<Editor @editorContent="editorContent" ref="richEditor" />
// 获取从富文本传过来的值
const editorContent = (obj) => {
//obj为富文本编辑的值
};
修改时富文本回显:
// 富文本默认值
const richEditor = ref(null);
nextTick(() => {
richEditor.value.content = row.content;//row.content列表返回值
});
效果图如下:
![](https://i-blog.csdnimg.cn/blog_migrate/3a59a6f7dfa4a9afaeb4a4a0899b0369.png)