vue-pure-admin富文本编辑器:WangEditor深度集成指南

【免费下载链接】vue-pure-admin 全面ESM+Vue3+Vite+Element-Plus+TypeScript编写的一款后台管理系统(兼容移动端) 【免费下载链接】vue-pure-admin 项目地址: https://gitcode.com/GitHub_Trending/vu/vue-pure-admin

引言

在现代化后台管理系统中,富文本编辑器是不可或缺的核心组件。你是否还在为选择哪款编辑器而烦恼?是否在集成过程中遇到各种兼容性问题?vue-pure-admin项目深度集成了WangEditor,提供了开箱即用的富文本编辑解决方案。本文将带你全面了解如何在vue-pure-admin中高效使用WangEditor,从基础配置到高级功能,一站式解决你的富文本编辑需求。

WangEditor版本与依赖

vue-pure-admin项目使用的WangEditor版本信息:

依赖包 版本号 功能描述
@wangeditor/editor ^5.1.23 核心编辑器库
@wangeditor/editor-for-vue ^5.1.12 Vue3适配器

基础集成配置

1. 安装依赖

项目已内置WangEditor依赖,如需手动安装:

pnpm add @wangeditor/editor @wangeditor/editor-for-vue

2. 基础编辑器组件

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";

defineOptions({
  name: "BaseEditor"
});

const mode = "default";
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>你好</p>");

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = "<p>我是模拟的异步数据</p>";
  }, 1500);
});

const toolbarConfig: any = { excludeKeys: "fullScreen" };
const editorConfig = { placeholder: "请输入内容..." };

const handleCreated = editor => {
  // 记录 editor 实例,重要!
  editorRef.value = editor;
};

// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<template>
  <div class="wangeditor">
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      style="height: 500px; overflow-y: hidden"
      @onCreated="handleCreated"
    />
  </div>
</template>

核心功能详解

1. 工具栏配置

WangEditor提供了丰富的工具栏配置选项:

const toolbarConfig = {
  // 排除不需要的工具栏按钮
  excludeKeys: [
    "group-video",
    "insertTable",
    "codeBlock",
    "|",
    "group-more-style"
  ],
  
  // 或者指定需要的工具栏按钮
  insertKeys: {
    index: 5,
    keys: ["emotion", "|", "insertLink", "insertImage"]
  }
};

2. 编辑器配置

const editorConfig = {
  placeholder: "请输入内容...",
  autoFocus: false,
  scroll: true,
  readOnly: false,
  maxLength: 10000,
  onMaxLength: () => {
    console.log("字数超出限制");
  },
  MENU_CONF: {
    // 图片上传配置
    uploadImage: {
      server: "/api/upload",
      fieldName: "file",
      maxFileSize: 10 * 1024 * 1024, // 10M
      allowedFileTypes: ["image/*"],
      withCredentials: true,
      timeout: 30 * 1000,
      onBeforeUpload: file => {
        console.log("上传前", file);
        return file;
      },
      onSuccess: (file, res) => {
        console.log("上传成功", file, res);
      },
      onFailed: (file, res) => {
        console.log("上传失败", file, res);
      },
      onError: (file, err, res) => {
        console.log("上传错误", file, err, res);
      },
      customInsert: (res, insertFn) => {
        // 自定义插入逻辑
        insertFn(res.data.url);
      }
    }
  }
};

高级功能实现

1. 多编辑器实例管理

在实际业务中,经常需要同时管理多个编辑器实例:

<script setup lang="ts">
import ReCol from "@/components/ReCol";
import { onBeforeUnmount, ref, shallowRef } from "vue";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

defineOptions({
  name: "MultiEditor"
});

// 模拟后端返回多个编辑器的数据
const endEditorList = [
  { value: "<p>测试一</p>" },
  { value: "<p>测试二</p>" },
  { value: "<p>测试三</p>" },
  { value: "<p>测试四</p>" }
];

// 多个编辑器的情况下,前端必须进行处理
const editorList = ref([]);
endEditorList.forEach(edit => {
  editorList.value.push({
    value: edit.value,
    // 编辑器实例,必须用 shallowRef
    editorRef: shallowRef()
  });
});

const mode = "default";
const toolbarConfig: any = { excludeKeys: "fullScreen" };
const editorConfig = { placeholder: "请输入内容..." };

const handleCreated = (editor, index) => {
  // 记录 editor 实例,重要!
  editorList.value[index].editorRef = editor;
};

// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
  return editorList.value.map(edit => {
    if (edit.editorRef == null) return;
    edit.editorRef.destroy();
  });
});
</script>

<template>
  <el-row :gutter="30" justify="space-around">
    <re-col v-for="(edit, index) in editorList" :key="index" :value="11">
      <div class="wangeditor">
        <Toolbar
          :editor="edit.editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
          style="border-bottom: 1px solid #ccc"
        />
        <Editor
          v-model="edit.value"
          :defaultConfig="editorConfig"
          :mode="mode"
          style="height: 300px; overflow-y: hidden"
          @onCreated="editor => handleCreated(editor, index)"
        />
      </div>
    </re-col>
  </el-row>
</template>

2. 自定义图片上传

<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef } from "vue";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

defineOptions({
  name: "picUpload"
});

const mode = "default";
const editorRef = shallowRef();
const valueHtml = ref("<p>自定义图片上传示例</p>");

const toolbarConfig: any = { excludeKeys: "fullScreen" };
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} };

// 图片上传配置
editorConfig.MENU_CONF["uploadImage"] = {
  server: "/api/upload/image",
  fieldName: "file",
  allowedFileTypes: ["image/png", "image/jpg", "image/jpeg"],
  maxFileSize: 5 * 1024 * 1024,
  headers: {
    Authorization: "Bearer your-token"
  },
  customInsert(res: any, insertFn) {
    if (res.code === 200 && res.data.url) {
      // 模拟异步插入
      setTimeout(() => {
        insertFn(res.data.url, "图片描述", res.data.url);
      }, 1000);
    } else {
      console.error("上传失败", res);
    }
  },
  onBeforeUpload(file) {
    console.log("准备上传", file);
    return file;
  },
  onSuccess(file, res) {
    console.log("上传成功", file, res);
  },
  onFailed(file, res) {
    console.log("上传失败", file, res);
  }
};

const handleCreated = editor => {
  editorRef.value = editor;
};

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

最佳实践与性能优化

1. 编辑器生命周期管理

// 正确的实例管理
const editorRef = shallowRef(); // 必须使用 shallowRef

// 创建时的回调
const handleCreated = (editor) => {
  editorRef.value = editor;
  // 可以在这里注册自定义事件
  editorRef.value.on('fullScreen', () => {
    console.log('全屏状态改变');
  });
};

// 销毁时的清理
onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy();
    editorRef.value = null;
  }
});

2. 内容验证与处理

// 获取纯文本内容
const getPlainText = () => {
  return editorRef.value.getText();
};

// 获取HTML内容
const getHtmlContent = () => {
  return editorRef.value.getHtml();
};

// 内容验证
const validateContent = () => {
  const content = editorRef.value.getText();
  if (content.trim().length === 0) {
    return "内容不能为空";
  }
  if (content.length > 10000) {
    return "内容长度不能超过10000字";
  }
  return null;
};

3. 主题与样式定制

/* 自定义编辑器样式 */
.wangeditor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.wangeditor .w-e-text-container {
  background-color: #fafafa;
}

.wangeditor .w-e-toolbar {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.wangeditor .w-e-menu {
  color: #606266;
}

.wangeditor .w-e-menu:hover {
  color: #409eff;
  background-color: #ecf5ff;
}

常见问题解决方案

1. 编辑器实例管理问题

// 错误做法:使用 ref
const editorRef = ref(); // ❌ 会导致性能问题

// 正确做法:使用 shallowRef
const editorRef = shallowRef(); // ✅ 性能优化

2. 内存泄漏预防

// 必须在组件销毁时手动销毁编辑器
onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy();
    editorRef.value = null;
  }
});

3. 多语言支持

// 配置多语言
const editorConfig = {
  lang: 'zh-CN', // 支持 en, zh-CN
  // 其他配置...
};

功能对比表

功能特性 WangEditor 其他编辑器 优势说明
体积大小 ~500KB 1-2MB 轻量级,加载更快
Vue3支持 原生支持 需要适配 更好的兼容性
类型定义 完整TS支持 部分支持 开发体验更好
自定义扩展 高度可配置 有限定制 灵活性更强
移动端适配 优秀 一般 响应式设计

集成流程图

mermaid

总结

vue-pure-admin项目通过深度集成WangEditor,为开发者提供了开箱即用的富文本编辑解决方案。本文详细介绍了从基础配置到高级功能的完整实现方案,包括:

  1. 基础集成:快速上手的基本配置和组件结构
  2. 核心功能:工具栏配置、编辑器选项、实例管理
  3. 高级特性:多编辑器管理、自定义上传、主题定制
  4. 最佳实践:性能优化、内存管理、错误处理
  5. 问题解决:常见问题及解决方案

通过本文的指南,你可以轻松在vue-pure-admin项目中实现强大的富文本编辑功能,提升用户体验和开发效率。WangEditor的轻量级设计和丰富功能使其成为后台管理系统编辑器的理想选择。

记得在实际项目中根据具体业务需求调整配置,特别是图片上传、内容验证等关键功能。Happy coding!

【免费下载链接】vue-pure-admin 全面ESM+Vue3+Vite+Element-Plus+TypeScript编写的一款后台管理系统(兼容移动端) 【免费下载链接】vue-pure-admin 项目地址: https://gitcode.com/GitHub_Trending/vu/vue-pure-admin

更多推荐