当前位置: 首页 > news >正文

Taro+Vue3实现微信小程序富文本编辑器组件开发指南

实现思路与核心逻辑

1. 组件设计思路

我们基于微信小程序原生editor组件进行封装,主要实现以下功能:

  • 工具栏配置:通过图标按钮提供格式控制

  • 双向数据绑定:支持内容获取与设置

  • 图片上传:集成图片选择与上传功能

  • 格式控制:封装常用文本格式方法

2. 关键技术点

  1. 编辑器实例管理:通过createSelectorQuery获取编辑器上下文

  2. 内容同步机制:使用getContentssetContents实现内容双向绑定

  3. 图片处理流程:整合chooseImageuploadFileAPI实现图片上传

  4. 格式控制方法:统一封装format方法处理各种文本格式

  5. 事件处理:正确处理小程序特有的事件命名规则(首字母大写)

    完整实现代码

    核心代码

    <!-- RichTextEditor.vue -->
    <template><view :class="styles.editor_box"><!-- 工具栏 --><view :class="styles.tooltar" v-if="showToolbar"><view v-for="(item, index) in ToolBarList" @tap="item.fnc()" :key="index"><image :src="item.icon" :class="styles.img" /></view></view><!-- 编辑器主体 --><editorid="editor":placeholder="placeholder"@ready="editorReady"@Input="handleEditorChange":style="editorStyle"/></view>
    </template><script setup lang="ts">
    import Taro from '@tarojs/taro';
    import { ref, withDefaults } from 'vue';
    import styles from './index.module.scss';// 类型定义
    type FormatType = 'bold' | 'italic' | 'header' | 'align' | 'list';
    type FormatValue = 'h1' | 'h2' | 'h3' | 'left' | 'right' | 'ordered' | 'bullet';interface EditorProps {showToolbar?: boolean;defaultContent?: string;placeholder?: string;
    }// 组件属性
    const props = withDefaults(defineProps<EditorProps>(), {showToolbar: true,placeholder: '请输入内容',defaultContent: ''
    });const emits = defineEmits(['editorChange']);// 编辑器实例与状态
    const editorCtx = ref<any>(null);
    const isEditorReady = ref(false);
    const editorStyle = ref('color: black; padding: 12rpx');// 工具栏配置
    const ToolBarList = [{ fnc: insertImage, icon: '实际图标链接', name: '插入图片' },{ fnc: () => formatText('italic'), icon: '实际图标链接', name: '斜体' },{ fnc: () => formatText('bold'), icon: '实际图标链接', name: '加粗' },{ fnc: () => formatText('header', 'h1'), icon: '实际图标链接', name: '标题1' },{ fnc: () => formatText('header', 'h2'), icon: '实际图标链接', name: '标题2' },{ fnc: () => formatText('header', 'h3'), icon: '实际图标链接', name: '标题3' },{ fnc: () => formatText('align', 'left'), icon: '实际图标链接', name: '左对齐' },{ fnc: () => formatText('align', 'right'), icon: '实际图标链接', name: '右对齐' },{ fnc: () => formatText('list', 'ordered'), icon: '实际图标链接', name: '有序列表' },{ fnc: () => formatText('list', 'bullet'), icon: '实际图标链接', name: '无序列表' },{ fnc: undo, icon: '实际图标链接', name: '撤销' }
    ];// 请求头配置
    const header = {'Content-Type': 'multipart/form-data',WEAPP_TOKEN_HEADER: xxxxxx,
    };// 初始化编辑器
    const editorReady = () => {Taro.createSelectorQuery().select('#editor').context((res) => {editorCtx.value = res.context;isEditorReady.value = true;if (props.defaultContent) {setEditorContent(props.defaultContent);}}).exec();
    };// 设置编辑器内容
    const setEditorContent = async (html: string) => {if (!editorCtx.value) return false;try {await editorCtx.value.setContents({ html });handleEditorChange();return true;} catch (err) {console.error('内容设置失败:', err);return false;}
    };// 获取编辑器内容
    const getEditorContent = () => {return new Promise((resolve) => {if (!editorCtx.value) return resolve(null);editorCtx.value.getContents({success: (res) => resolve({ html: res.html, text: res.text }),fail: (err) => {console.error('内容获取失败:', err);resolve(null);}});});
    };// 内容变化回调
    const handleEditorChange = async () => {const content = await getEditorContent();if (content) emits('editorChange', content);
    };// 文本格式控制
    const formatText = (type: FormatType, value?: FormatValue) => {if (editorCtx.value) editorCtx.value.format(type, value);
    };// 撤销操作
    const undo = () => {if (editorCtx.value) editorCtx.value.undo();
    };// 插入图片
    const insertImage = () => {Taro.chooseImage({count: 1,sizeType: ['compressed'],sourceType: ['album', 'camera'],success: async (res) => {Taro.showLoading({ title: '上传中...' });const filePath = res.tempFilePaths[0];try {const uploadRes = await Taro.uploadFile({url: `实际后台服务器地址`,filePath,header,name: 'file'});const data = JSON.parse(uploadRes.data);if (data?.data?.error) {throw new Error(data.data.error);}if (editorCtx.value) {await editorCtx.value.insertImage({src: data.data,width: '100%'});Taro.showToast({ title: '插入成功', icon: 'success' });}} catch (error) {Taro.showToast({ title: '上传失败', icon: 'error' });console.error('图片上传失败:', error);} finally {Taro.hideLoading();}}});
    };
    </script>
    

    index.module.scss 样式文件
     

    .editor_box {width: 100%;height: auto;box-sizing: border-box;background: #F7F7F7;border-radius: 12rpx;
    }.tooltar{display: flex;align-items: center;justify-content: space-between;box-sizing: border-box;padding: 10rpx 12rpx;border-bottom: 1rpx solid #EBEBEB;view{.img{width: 24rpx;height: 24rpx;}}
    }
    

    2. 方法说明

    方法名说明参数
    setEditorContent设置编辑器内容html: string
    getEditorContent获取编辑器内容
    formatText格式化文本type: FormatType, value?: FormatValue
    insertImage插入图片
    undo撤销操作

    3. 注意事项

  • 图片上传需要配置正确的服务器地址和认证信息

  • 编辑器样式在小程序中只能使用内联样式

  • 内容变化事件会频繁触发,建议在父组件中添加防抖处理

  • 需要提前准备好工具栏所需的图标资源

http://www.dtcms.com/a/268832.html

相关文章:

  • RoboRefer:面向机器人视觉-语言模型推理的空间参考
  • 数学建模从入门到国奖——备赛规划优秀论文学习方法
  • 在 Windows 系统上配置 [go-zero](https://go-zero.dev) 开发环境教程
  • React-React.memo-props比较机制
  • 基于YOLOv11的车辆检测系统项目教程(Python源码+Flask Web界面+数据集)
  • AI智能体长期记忆系统架构设计与落地实践:从理论到生产部署
  • [论文阅读] 人工智能 | 读懂Meta-Fair:让LLM摆脱偏见的自动化测试新方法
  • Mac 电脑无法读取硬盘的解决方案
  • Redisson详细教程 - 从入门到精通
  • zookeeper介绍
  • PostgreSQL性能优化实践指南:从原理到实战
  • 大语言模型(LLM)课程学习(Curriculum Learning)、数据课程(data curriculum)指南:从原理到实践
  • 知识竞赛答题pk小程序用户操作手册
  • Linux内核ext4 extent:解决大文件存储难题的关键
  • MybatisPlus(一)扩展功能
  • MS51224 一款 16 位、3MSPS、双通道、同步采样模数转换器(ADC)
  • LMH1219RTWR-富利威-3G/12G-SDI
  • 【mini-spring】【更新中】第一章 IOC与Bean源码及思路解析
  • 如何用 Mockito 玩转单元测试
  • 闲庭信步使用图像验证平台加速FPGA的开发:第三课——YCbCr转RGB的FPGA实现
  • 搜广推校招面经八十八
  • Linux批量执行工具脚本使用指南:一键运行多个release-dev.sh脚本
  • macOS运行python程序遇libiomp5.dylib库冲突错误解决方案
  • 【STM32】const 变量存储学习笔记
  • 【论文阅读】CogView: Mastering Text-to-Image Generation via Transformers
  • 文心一言4.5开源模型测评:ERNIE-4.5-0.3B超轻量模型部署指南
  • React19 新增Hooks:useOptimistic
  • 巧借东风:32位栈迁移破解ciscn_2019_es_2的空间困局
  • maven 发布到中央仓库-01-概览
  • 23、企业租赁管理(Rent)全流程指南:从资产盘活到价值最大化的数字化实践