vue3+ts项目引入富文本编辑器wangeditor
说明
项目开发中,做到媒体说、资讯等模块时,会需要引入富文本编辑器,对比发现wangeditor使用群众多,并且很多问题也已经有解答。
界面展示
实现要点
- 引入wangeditor
npm install --save @wangeditor/editor @wangeditor/editor-for-vue@next
- 配置导航栏
代码
<template> <div style="border: 1px solid #EEEFF0;border-radius: 5px;overflow: hidden;width: 100%;"> <Toolbar style="border-bottom: 1px solid #EEEFF0" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" /> <Editor style="height: 500px; overflow-y: hidden;" v-model="modelValue" @on-change="handleChange" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" /> </div> </template> <script setup lang="ts"> import { uploadFileApi } from '@/api/upfile'; import { Editor, Toolbar } from '@wangeditor/editor-for-vue' import { shallowRef } from 'vue'; import { IToolbarConfig, DomEditor } from '@wangeditor/editor' const toolbarConfig: Partial<IToolbarConfig> = { toolbarKeys: ['headerSelect', 'bold', 'italic', 'underline', 'through', 'bulletedList', 'justifyLeft','justifyCenter','justifyRight', 'undo', 'redo','uploadImage', 'insertLink'] } const editorRef = shallowRef() const mode = 'default' const props = defineProps({ modelValue: { type: [String], default: "" } }) const emit = defineEmits(['update:modelValue']) const modelValue = useVModel(props, 'modelValue', emit) const editorConfig = { MENU_CONF: { uploadImage: { // 自定义图片上传 async customUpload(file: any, insertFn: any) { uploadFileApi(file).then((response) => { const url = response.data.src; insertFn(url); }); }, }, }, } const handleCreated = (editor: any) => { editorRef.value = editor } const handleChange = (editor: any) => { modelValue.value = editor.isEmpty() ? "" : editor.getHtml(); } onBeforeUnmount(() => { const editor = editorRef.value; if (editor == null) return; editor.destroy(); }); </script> <style src="@wangeditor/editor/dist/css/style.css"></style>
注:在自定义组件时,修改modelValue时需要通过isEmpty()这个方法去校验内容是否为空,editor初始化时会将内容赋为<p><br/></p>,就会使表单非空校验失效。
wangeditor配置
- 打印配置选项(在handleCreated中打印)
const handleCreated = (editor: any) => { editorRef.value = editor nextTick(() => { const toolbar = DomEditor.getToolbar(editor) const curToolbarConfig = toolbar?.getConfig().toolbarKeys console.log('curToolbarConfig---',curToolbarConfig) }) }
- 删除某些选项
const toolbarConfig: Partial<IToolbarConfig> = { excludeKeys: ['group-video','divider','emotion','fullScreen'] }
- 直接配置某些选项
const toolbarConfig: Partial<IToolbarConfig> = {
toolbarKeys: ['headerSelect', 'bold', 'italic', 'underline', 'through', 'bulletedList', 'justifyLeft','justifyCenter','justifyRight', 'undo', 'redo','uploadImage', 'insertLink']
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)