首先需要安装插件
npm add vue-ueditor-wrap
或
pnpm add vue-ueditor-wrap
这里我用的是我自己的包,不是官方的
然后下载压缩包解压至项目中的public文件夹里面
然后再main.js 里面配置,引入我们的富文本插件
import { createApp } from 'vue';
import pinia from '/@/stores/index';
import App from '/@/App.vue';
import router from '/@/router';
import { directive } from '/@/directive/index';
import { i18n } from '/@/i18n/index';
import other from '/@/utils/other';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import ElementPlus from 'element-plus';
import '/@/theme/index.scss';
import VueGridLayout from 'vue-grid-layout';
// 引入 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);
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component);
}
app.use(pinia).use(router).use(ElementPlus).use(i18n).use(VueGridLayout).mount('#app');
然后再src目录下方的components文件夹里面创建文件UEditor.vue进行配置
<!-- src/components/UEditor.vue -->
<template>
<div ref="editor"></div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
// 声明 UEditor 全局变量
declare const UE: any;
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: "pc/Fileimg/uderto", // 根据实际情况配置
});
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;
// });
// }
};
watch(
() => props.modelValue,
(newValue) => {
if (ueditorInstance && newValue !== ueditorInstance.getContent()) {
ueditorInstance.setContent(newValue);
}
}
);
</script>
<style scoped>
/* 可以根据需要添加样式 */
</style>
配置完成之后,在你所需页面引入使用
import UEditor from "/@/components/UEditor.vue";// 富文本引入
在所需要使用的地方写
<UEditor v-model.trim="form.content" @input="form.content = $event" v-trim />
<!-- 富文本使用 -->
如果你需要上传图片,上传图片报错,说未配置
serverUrl:"/pcapi/editor/index",//根据实际情况配置,serverUrl修改成自己的富文本编辑的接口即可。
如果还有其他地方不懂的,可以上网搜索🌹