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组件的属性即可。。。。

相关推荐
克里斯蒂亚诺更新21 小时前
微信小程序使用vant4 weapp自定义菜单 但是弹出层却被菜单遮挡的解决办法
微信小程序·小程序·notepad++
静Yu1 天前
从一个九宫格素材小程序,看轻量工具产品该如何优化体验
前端·微信小程序
小羊Yveesss1 天前
2026年微信小程序制作工具怎么选?
微信小程序·小程序
脱脱克克1 天前
使用 TRAE / VS Code + DeepSeek V4 开发微信小程序、网页
微信小程序·ai编程·环境配置
前端 贾公子1 天前
使用 wxappUnpacker 工具进行 MAC 微信小程序反编译
macos·微信小程序·小程序
爱分享的小诺2 天前
微信小程序2.0人脸审核,1.0升级到2.0
微信小程序·小程序
打瞌睡的朱尤2 天前
微信小程序(黑马)4-5
微信小程序·小程序
凌奕3 天前
微信小程序接入微信 AI:让用户"说一句话"就能下单
微信·微信小程序·agent
倒流时光三十年3 天前
第十八章 搜索历史保存功能实现记录
spring boot·微信小程序
倒流时光三十年3 天前
第十七章 投票页面增加搜索功能
spring boot·微信小程序