介绍
在现代Web应用中,富文本编辑器是不可或缺的组件。本文将详细介绍如何在Vue3项目中集成wangEditor,一个轻量级、功能强大的Web富文本编辑器。
安装与配置
首先,我们需要安装wangEditor的相关依赖:
npm install @wangeditor/editor@^5.1.23 @wangeditor/editor-for-vue@5.1.12
组件实现
下面是完整的富文本编辑器组件实现代码:
<template>
<div style="border: 1px solid #ccc" class="w-full h-full">
<Toolbar
style="border-bottom: 1px solid #ccc"
:editor="editorRef"
:defaultConfig="toolbarConfig"
:mode="'default'"
/>
<Editor
style="height: 500px; overflow-y: hidden"
v-model="valueHtml"
:defaultConfig="editorConfig"
:mode="'default'"
@onChange="handleChange"
@onCreated="handleCreated"
/>
</div>
</template>
<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
defineOptions({ name: "MyEditor" });
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("<p>hello</p>");
const emits = defineEmits(["change"]);
// 模拟 ajax 异步获取内容
onMounted(() => {
setTimeout(() => {
valueHtml.value = "<p>模拟 Ajax 异步设置内容</p>";
}, 1500);
});
const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value;
if (editor == null) return;
editor.destroy();
});
// 编辑器创建完毕时的回调函数
const handleCreated = (editor: any) => {
editorRef.value = editor; // 记录 editor 实例,重要!
};
// 编辑器 Change 时的回调函数
const handleChange = (editor: any) => {
const data = {
html: editor.getHtml() == "<p><br></p>" ? "" : editor.getHtml(),
text: editor.getText(),
};
console.log(data);
emits("change", data);
};
</script>
关键点解析
-
编辑器实例管理:
-
使用
shallowRef
来存储编辑器实例,这是wangEditor的推荐做法 -
在组件销毁时调用
editor.destroy()
进行清理
-
-
双向绑定:
-
通过
v-model
绑定valueHtml
实现内容双向绑定 -
提供
onChange
事件处理内容变化
-
-
配置选项:
-
toolbarConfig
:配置工具栏按钮 -
editorConfig
:配置编辑器行为,如占位文本
-
-
异步内容加载:
-
演示了如何异步设置编辑器内容
-
使用示例
在父组件中使用这个编辑器:
<template>
<div>
<MyEditor @change="handleEditorChange" />
</div>
</template>
<script setup>
import MyEditor from './MyEditor.vue';
const handleEditorChange = (data) => {
console.log('HTML内容:', data.html);
console.log('纯文本内容:', data.text);
};
</script>
高级配置
自定义工具栏
const toolbarConfig = {
excludeKeys: [
'headerSelect',
'italic',
'group-more-style' // 排除菜单组,写菜单组 key 的值即可
]
}
扩展编辑器功能
const editorConfig = {
placeholder: '请输入内容...',
MENU_CONF: {
uploadImage: {
server: '/api/upload-image',
fieldName: 'image'
}
}
}
总结
wangEditor为Vue3提供了简单易用的富文本编辑解决方案。通过本文的组件实现,你可以快速在项目中集成功能完善的富文本编辑器,并根据需要进行定制扩展。这种实现方式既保持了编辑器的完整功能,又能很好地融入Vue3的响应式系统。