效果图
- 下载依赖包
@pureadmin/utils": "2.4.7
@wangeditor/editor": "^5.1.23
@wangeditor/editor-for-vue": "5.1.12
- 定义公共组件
在src目录下定义 components/ReEditor/index.vue
index.ts
import editor from "./src/Editor.vue";
import { withInstall } from "@pureadmin/utils";
/** 编辑器组件 */
export const RwEditor = withInstall(editor);
export default RwEditor;
Editor.vue
<script setup>
import { onBeforeUnmount, onMounted, ref, shallowRef, watchEffect } from "vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
defineOptions({
name: "Editor"
});
const props = defineProps({
mode: {
type: String,
requred: true
},
toolbarConfig: {
type: Object,
default: () => {
return {
excludeKeys: ["fullScreen", "emotion", "group-image", "group-video"]
};
}
},
editorConfig: {
type: Object,
default: () => {
return { placeholder: "请输入内容..." };
}
},
initValue: {
type: String,
default: ""
},
height: {
type: String,
default: "500px"
}
});
const emit = defineEmits(["changeVal"]);
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("");
watchEffect(() => {
valueHtml.value = props.initValue;
});
onMounted(() => {});
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value;
if (editor != null) {
editor.clear();
} else {
return;
}
editor.destroy();
});
const handleCreated = editor => {
editorRef.value = editor; // 记录 editor 实例,重要!
// console.log(editor.getHtml());
};
const handleChange = editor => {
emit("changeVal", editor.getHtml());
};
</script>
<template>
<div class="wangeditor">
<Toolbar
style="border-bottom: 1px solid #ccc"
:editor="editorRef"
:defaultConfig="props.toolbarConfig"
:mode="props.mode"
/>
<Editor
:style="{ height: props.height, overflowY: 'hidden' }"
v-model="valueHtml"
:defaultConfig="props.editorConfig"
:mode="props.mode"
@onCreated="handleCreated"
@onChange="handleChange"
/>
</div>
</template>
<style lang="scss" scoped></style>
- 引用
在使用.vue页面
<script setup lang="ts">
import { RwEditor } from "@/components/RwEditor";
const importExcel = (res:any) => {
return Base64.encode(res);
};
const content = ref("");
const changeVal = v => {
content.value = v;
};
const submit = () => {
content.value = importExcel(content.value)
接口url(入参).then(res => {
ElMessage.success("导入成功");
content.value = "";
});
};
</script>
<template>
<el-dialog
v-model="dialogVisible"
title="导入数据"
width="60%"
>
<RwEditor @changeVal="changeVal" :init-value="content" :height="'300px'"/>
<template #footer>
<el-button type="primary" @click="submit" :loading="loading">确定</el-button>
</template>
</el-dialog>
</template>