1.安装
npm add vue-ueditor-wrap 或者 pnpm add vue-ueditor-wrap 进行安装
2、下载UEditor
官网:ueditor:rich text 富文本编辑器 - GitCode
整理好的:vue-ueditor: 百度编辑器JSP版
因为官方的我没用来,所以我自己找的另外的包
安装依赖 npm i vue-ueditor-wrap@3.x -S
3、把下载好的包放在项目目录下 /public下
4、main.js配置,引入富文本插件。
// src/main.ts
import { createApp } from 'vue';
import pinia from '/@/stores/index';
import App from '/@/App.vue';
import router from '/@/router';
import { directive } from '/@/directive/index';
import other from '/@/utils/other';import ElementPlus from 'element-plus';
import '/@/theme/index.scss';// 引入 UEditor 富文本插件
import '/public/ueditor/ueditor.config.js';
import '/public/ueditor/ueditor.all.min.js';
import '/public/ueditor/lang/zh-cn/zh-cn.js';
import '/public/ueditor/themes/default/css/ueditor.css'; // 确保引入 UEditor 的 CSS 文件const app = createApp(App);directive(app);
other.elSvg(app);app.use(pinia).use(router).use(ElementPlus).mount('#app');
5、给富文本封装到components文件夹中新建富文本文件夹- UEditor.vue文件夹。
在UEditor.vue复制一下内容:
<!-- src/components/UEditor.vue -->
<template><div ref="editor"></div>
</template><script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from "vue";const props = defineProps({modelValue: {type: String,default: "",},
});const emit = defineEmits(["update:modelValue"]);const editor = ref(null);
let ueditorInstance: any = null;onMounted(() => {nextTick(() => {initUEditor();});
});onBeforeUnmount(() => {destroyUEditor();
});const initUEditor = () => {nextTick(() => {ueditorInstance = UE.getEditor(editor.value, {initialFrameWidth: "95%",initialFrameHeight: 200,serverUrl: "/pcapi/editor/index", // 根据实际情况配置});ueditorInstance.ready(() => {ueditorInstance.setContent(props.modelValue);ueditorInstance.addListener("contentChange", () => {emit("update:modelValue", ueditorInstance.getContent());});});});
};const destroyUEditor = () => {UE.delEditor(editor.value);// if (ueditorInstance) {// // 尝试在下一次事件循环中销毁实例,确保不会影响其他操作// nextTick(() => {// ueditorInstance.destroy();// ueditorInstance = null;// });// }console.log("destroyUEditor");
};watch(() => props.modelValue,(newValue) => {if (ueditorInstance && newValue !== ueditorInstance.getContent()) {ueditorInstance.setContent(newValue);}}
);
</script><style scoped>
/* 可以根据需要添加样式 */
</style>
6.需要在哪一页使用就引入
// 富文本引入
import UEditor from "/@/components/UEditor.vue";
需要富文本的地方写
<el-form-item label="内容:" :label-width="formLabelWidth" prop="content"><UEditor v-model="form.content" /></el-form-item>
7、上传图片报错,说什么未配置
serverUrl修改成自己的富文本编辑的接口即可。