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

相关推荐
lvbb6641 分钟前
微信小程序-路线规划功能
微信小程序·小程序·notepad++
爱上大树的小猪3 小时前
微信小程序模仿快播标签云滚动特效
微信小程序·小程序
從南走到北7 小时前
挪车小程序挪车二维码php+uniapp
微信小程序·小程序·开源·微信公众平台
Java Fans10 小时前
微信小程序——访问服务器媒体文件的实现步骤
服务器·微信小程序·小程序
Evaporator Core13 小时前
微信小程序数据绑定与事件处理:打造动态交互体验
微信小程序·小程序·交互
流烟默1 天前
vue和微信小程序处理markdown格式数据
前端·vue.js·微信小程序
乔冠宇1 天前
微信小程序中将图片截图为正方形(自动居中)
微信小程序·小程序·typescript·uniapp
V+zmm101341 天前
在线办公小程序(springboot论文源码调试讲解)
vue.js·spring boot·微信小程序·小程序·毕业设计
V+zmm101341 天前
自驾游拼团小程序的设计与实现(ssm论文源码调试讲解)
java·数据库·微信小程序·小程序·毕业设计
黑马源码库miui520862 天前
挪车小程序挪车二维码php+uniapp
微信小程序·小程序·微信公众平台