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

相关推荐
狂团商城小师妹10 小时前
JAVA露营基地预约户外露营预约下单系统小程序
java·开发语言·微信小程序·小程序
知识分享小能手13 小时前
微信小程序入门学习教程,从入门到精通,微信小程序页面制作(2)
前端·javascript·学习·微信小程序·小程序·前端框架·notepad++
计算机毕业设计小帅16 小时前
【2026计算机毕业设计】基于Springboot的汉服交流的微信小程序
spring boot·微信小程序·课程设计
OEC小胖胖17 小时前
组件化思维(下):表单与交互组件,倾听用户的心声
前端·微信小程序·小程序·微信开放平台
云起SAAS1 天前
老年ai模拟恋爱抖音快手微信小程序看广告流量主开源
人工智能·微信小程序·小程序·ai编程·看广告变现轻·老年ai模拟恋爱·ai模拟恋爱
宠友信息1 天前
类似小红书垂直社区APP小程序源码
java·开发语言·微信小程序·小程序·uni-app·开源·web app
Stanford_11061 天前
关于单片机的原理与应用!
c++·单片机·嵌入式硬件·微信小程序·微信公众平台·微信开放平台
OEC小胖胖1 天前
交互的脉络:小程序事件系统详解
前端·微信小程序·小程序·微信开放平台
毕设源码-邱学长2 天前
【开题答辩全过程】以 “勤工有道”微信小程序为例,包含答辩的问题和答案
微信小程序·小程序