遥舟客 - wangeditor
type: channel
link: https://www.renlmingj.cn/index.php/tag/wangeditor/
items: vue3+js+wangeditor插件使用

vue3+js+wangeditor插件使用
type: item
date: 2025-07-08T17:31:00+08:00
description: 一、安装yarn add @wangeditor/editor 或者 npm install @wangeditor/editor --save二、组件封装新建 wangEditor.vue 文件1、html代码 <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" /> <Editor style="min-height: 300px;max-height: 400px;overflow-y: auto;" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" @onChange="handleChange" /> 2、js代码import "@wangeditor/editor/dist/css/style.css"; // 引入 css import { onBeforeUnmount, ref, shallowRef, defineProps } from "vue"; import { Editor, Toolbar } from "@wangeditor/editor-for-vue"; // 传值到父级 const emit = defineEmits(["update"]); // 内容 HTML const valueHtml = ref(""); const mode = ref("default"); // 编辑器模式，默认 'default' 或 'simple' const { value } = defineProps({ value: { type: String, default: "" } }); valueHtml.value = value; // 将传入的 value 赋值给 valueHtml // 编辑器实例，必须用 shallowRef const editorRef = shallowRef(); const editorConfig = { placeholder: '请输入内容', scroll: true, // 是否开启滚动条 autoFocus: false, // 是否自动获取焦点 }; const toolbarConfig = {}; toolbarConfig.excludeKeys = [ "group-video", // 排除菜单组，写菜单组 key 的值即可 "todo", "insertLink", "blockquote", "group-image", ]; // 组件销毁时，也及时销毁编辑器 onBeforeUnmount(() => { const editor = editorRef.value; if (editor == null) return; editor.destroy(); }); const handleCreated = (editor) => { editorRef.value = editor; // 记录 editor 实例，重要！ }; // 每次编辑器内容变化时触发 const handleChange = (editor) => { // 获取最新的HTML内容 valueHtml.value = editor.getHtml() // 触发更新事件 emit('update', valueHtml.value) }三、父级调用1、html代码<wang-editor :value="content" style="width: 80%;" @update="privacyHandle" />2、js代码import { ref } from 'vue'; import wangEditor from "@/components/wangEditor.vue"; // 富文本值 const content = ref(""); // 隐私政策内容变化时触发 const privacyHandle = (value) => { content.value = value; }四、效果图