uni微信小程序editor富文本组件如何插入图片

需求

在editor中插入图片,并对图片进行编辑,简略看一下组件的属性,官网editor 组件 | uni-app官网

解决方案

首先要使用到@ready这个属性,然后官网有给代码粘过来,简单解释一下这段代码的意思(作用是在不同平台下获取编辑器的上下文,以便后续对编辑器进行操作,比如插入图片、获取内容等)

HTML

html 复制代码
<editor id="editor" ref="editor" @ready="onEditorReady" >
</editor>

JS

javascript 复制代码
onEditorReady() {
				// #ifdef MP-BAIDU
				this.editorCtx = requireDynamicLib('editorLib').createEditorContext('editor');
				// #endif

				// #ifdef APP-PLUS || MP-WEIXIN || H5
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
				}).exec()
				// #endif
},

然后添加一个按钮用来插入图片,这里直接上完整的代码

html 复制代码
<template>
  <view class="addForum_app">
    <!-- 编辑器组件 -->
    <editor id="editor" ref="editor" placeholder="请输入内容..." @ready="onEditorReady"></editor>
    <!-- 图片选择按钮 -->
    <button type="primary" @click="selectPhoto">选择图片</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      editorCtx: null, // 编辑器上下文对象
    };
  },
  methods: {
    // 编辑器准备完成
    onEditorReady() {
      uni.createSelectorQuery().select('#editor').context((res) => {
        this.editorCtx = res.context;
      }).exec();
    },
    // 选择图片
    selectPhoto() {
      uni.chooseImage({
        count: 9, // 最多可以选择的图片数量
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
        sourceType: ['album'], // 从相册选择
        success: (res) => {
          const tempFilePaths = res.tempFilePaths;
          // 遍历选中的图片路径,并使用 insertImage 方法将它们插入到编辑器中
          tempFilePaths.forEach((path) => {
            this.editorCtx.insertImage({
              src: path,
              success: function() {
                console.log('图片插入成功');
              }
            });
          });
        },
        fail: (err) => {
          console.error('选择照片失败:', err);
        }
      });
    }
  }
};
</script>

最后对图片的操作非常简单,查看官网的editor组件的属性即可。。。。

相关推荐
棋宣1 天前
微信小程序onShareAppMessage 分享-生命周期函数 在vue3中 组合式函数 hooks中不生效
微信小程序·小程序
好赞科技1 天前
深度测评2026年精选美发预约小程序排行榜 革新预约新体验 修订
大数据·微信小程序
一颗无敌码农2 天前
多商户与多门店电商系统有什么区别?核心模式解析
微信小程序·php·用户运营·crmeb
hhzz2 天前
记录微信小程序tabbar不显示问题:uni-app Vue 3 自定义 tabBar 不渲染
vue.js·微信小程序·uni-app
Greg_Zhong2 天前
微信小程序中调用豆包【免费】模型,实现小程序版ai助手完整版
微信小程序·豆包模型·调用豆包模型封装ai助手
30763 天前
uni-app在微信小程序国际化分包方案:优雅解决主包体积超限问题
微信小程序
打瞌睡的朱尤3 天前
微信小程序50~75
微信小程序·小程序
ZC跨境爬虫3 天前
【零基础实战】Fiddler抓取PC微信小程序数据流,爬取华为商城商品配置+真实评论(完整可运行代码+逐行解析)
测试工具·微信小程序·fiddler
tianxiaxue16 天前
微信小程序如何跟企微互通
微信小程序·小程序·企业微信
Greg_Zhong6 天前
微信小程序中canvas绘制面积图,解决手机和模拟器都能渲染不溢出问题
微信小程序·小程序canvas绘制面积图