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

相关推荐
2401_845937535 小时前
PHP一键约课高效健身智能健身管理系统小程序源码
微信·微信小程序·小程序·微信公众平台·微信开放平台
程序员入门进阶7 小时前
基于微信小程序的科创微应用平台设计与实现+ssm(lw+演示+源码+运行)
微信小程序·小程序
计算机源码社15 小时前
分享一个基于微信小程序的居家养老服务小程序 养老服务预约安卓app uniapp(源码、调试、LW、开题、PPT)
android·微信小程序·uni-app·毕业设计项目·毕业设计源码·计算机课程设计·计算机毕业设计开题
双普拉斯18 小时前
微信小程序点赞动画特效实现
nginx·微信小程序·notepad++
程序员阿龙18 小时前
【2025】基于微信小程序的网上点餐系统设计与实现、基于微信小程序的智能网上点餐系统、微信小程序点餐系统设计、智能点餐系统开发、微信小程序网上点餐平台设计
微信小程序·小程序·毕业设计·订单管理·在线点餐·订单跟踪·在线支付
Angus-zoe18 小时前
uniapp+vue+微信小程序实现侧边导航
vue.js·微信小程序·uni-app
开利网络1 天前
综合探索数字化转型的奥秘与前景
运维·微信小程序·自动化·产品运营·数字化营销
张人玉1 天前
微信小程序开发——比较两个数字大小
微信小程序·小程序
计算机学姐2 天前
基于微信小程序的食堂点餐预约管理系统
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
罗_三金2 天前
微信小程序读写NFC标签(实现NFC标签快速拉起小程序)实战
前端·javascript·微信小程序·小程序