Vue3:uv-upload图片上传

效果图:

参考文档:

Upload 上传 | 我的资料管理-uv-ui 是全面兼容vue3+2、nvue、app、h5、小程序等多端的uni-app生态框架 (uvui.cn)

代码:

html 复制代码
<view class="greenBtn_zw2" @click="handleAddGroup">添加班级群</view>
javascript 复制代码
  //添加班级群
  const handleAddGroup = () => {
    addDialog.value.open();
  };
html 复制代码
<!-- 添加班级群弹窗 -->
    <uv-popup ref="addDialog" mode="center" :customStyle="dialogStyle2" :closeOnClickOverlay="false">
      <view class="dialogBG">
        <view class="dialog-all">
          <view class="dialog-small-close" @click="cancelRoom">
            <uv-icon name="close-circle-fill" size="28" color="#B1B1B1"></uv-icon>
          </view>
          <view class="dialog-center">
            <view class="dialog-title pb-10">班级群</view>
            <view class="diaText">班级群名称</view>
            <uv-input maxlength="10" placeholder="请输入班级群名称" border="surround" clearable v-model="addGroup.info.groupName"></uv-input>
            <view class="diaText statusD">
              群二维码
              <view class="gray_s">
                <text style="margin-right: 38rpx; font-size: 28rpx; color: #555555">状态</text>
                <uv-switch v-model="addGroup.info.status" size="20" activeColor="#287e66" inactive-color="#c0c0c0" asyncChange @change="changeValue"></uv-switch>
              </view>
            </view>
            <view class="m-flex" style="align-items: center">
              <uv-upload
                :fileList="fileList"
                name="fileList"
                :maxCount="1"
                @afterRead="afterRead"
                @delete="deletePic"
                width="360rpx"
                height="360rpx"
                :customStyle="{ width: '360rpx', height: '360rpx', marginBottom: '40rpx', display: 'flex', alignItems: 'center' }"
              ></uv-upload>
            </view>
            <view class="dialog_footer1 displayFlexSB">
              <view class="common-sure-btn-1" @click="confirmRoom()">确定</view>
              <view class="common-sure-btn-2" @click="cancelRoom()">取消</view>
            </view>
          </view>
        </view>
      </view>
    </uv-popup>
javascript 复制代码
<script setup lang="ts"> 
  import { onLoad, onShow } from '@dcloudio/uni-app';
  import { ref, reactive, toRefs, onMounted, defineComponent } from 'vue';
  import { getFirstPage, getFirstClass, sessionUpdate, sessionCreate, sessionDelete } from '@/apis/vocabulary.ts';  

  const dialogStyle2 = reactive({ width: '597rpx', height: '855rpx', background: '#FFFFFF', borderRadius: '48rpx' });

  const addGroup = reactive<object>({ info: { groupName: '', status: true } });
  const fileList = ref([]);

  const validateClassForm = () => {
    if (addGroup.info.groupName == '') {
      toast.value.show({ message: '请输入班级群名称', success: false });
      return false;
    }
    if (addGroup.info.groupName.trim().length >= 11) {
      toast.value.show({ message: '班级群名称不能超过10个字符', success: false });
      return false;
    }
    if (fileList.value.length < 1) {
      toast.value.show({ message: '请上传群二维码', success: false });
      return false;
    }
    return true;
  };

    
  //关闭/取消 弹框按钮方法
  const cancelRoom = () => {
    addGroup.info = {
      groupName: '',
      status: true
    };
    fileList.value = [];
    addDialog.value.close();
  };


  //是否切换switch进行状态推送
  const changeValue = (e: any) => {
    uni.showModal({
      content: e ? `确定要开启${addGroup.info.groupName}吗` : `确定要关闭${addGroup.info.groupName}吗`,
      success: (res) => {
        if (res.confirm) {
          addGroup.info.status = e;
          console.log('e------', addGroup.info.status);
        }
      }
    });
  };


  //图片上传方法
  //afterRead读取后的处理函数
  const afterRead = async (event: any) => {
    // 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
    let lists = [].concat(event.file);
    let fileListLen = fileList.value.length;
    lists.map((item) => {
      fileList.value.push({
        ...item,
        status: 'uploading',
        message: '上传中'
      });
    });
    for (let i = 0; i < lists.length; i++) {
      const result = await uploadFilePromise(lists[i].url);
      // console.log(result, '1111111111111111');
      let item = fileList.value[fileListLen];
      fileList.value.splice(
        fileListLen,
        1,
        Object.assign(item, {
          status: 'success',
          message: '',
          url: result ? result : ''
        })
      );
      fileListLen++;
    }
  };

  const uploadFilePromise = (url) => {
    return new Promise((resolve, reject) => {
      let a = uni.uploadFile({
        // url: `${config.baseURL}/zx/common/uploadFile`, // 仅为示例,非真实的接口地址
        url: 'https://baiduway.baijy.com/zx/common/uploadFile', // 仅为示例,非真实的接口地址
        filePath: url,
        name: 'file',
        // formData: {
        //   user: 'test'
        // },
        header: {
          Token: uni.getStorageSync('token')
        },
        success: (res) => {
          let result = JSON.parse(res.data);
          setTimeout(() => {
            resolve(result.data.fileUrl);
          }, 1000);
        }
      });
    });
  };


  // 删除图片
  const deletePic = (event: any) => {
    console.log(event);
    console.log('fileList.value', fileList.value);
    console.log('fileList${event.name}', `fileList${event.name}`);
    // fileList[event.name]
    fileList.value.splice(event.index, 1);
    // this[`fileList${event.name}`].splice(event.index, 1);
  };


  //确定方法
  const confirmRoom = () => {
    if (validateClassForm()) {
      let obj = {
        groupName: addGroup.info.groupName,
        status: addGroup.info.status ? 1 : 0,
        qrcodeUrl: fileList.value[0].url
      };
      addGroupList(obj).then((res: any) => {
        if (res.success) {
          toast.value.show({ message: '班级群添加成功', success: true });
          getclassList();
          cancelRoom();
        } else {
          toast.value.show({ message: res.message, success: false });
        }
      });
    }
  };

</script>
相关推荐
不知名raver(学python版)7 分钟前
npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR!
前端·npm·node.js
醉方休17 分钟前
React中使用DDD(领域驱动设计)
前端·react.js·前端框架
excel23 分钟前
📖 小说网站的预导航实战:link 预加载 + fetch + 前进后退全支持
前端
学习3人组26 分钟前
React 样式隔离核心方法和最佳实践
前端·react.js·前端框架
世伟爱吗喽32 分钟前
threejs入门学习日记
前端·javascript·three.js
朝阳5811 小时前
用 Rust + Actix-Web 打造“Hello, WebSocket!”——从握手到回声,只需 50 行代码
前端·websocket·rust
F2E_Zhangmo1 小时前
基于cornerstone3D的dicom影像浏览器 第五章 在Displayer四个角落显示信息
开发语言·前端·javascript
slim~1 小时前
javaweb基础第一天总结(HTML-CSS)
前端·css·html
一支鱼1 小时前
leetcode常用解题方案总结
前端·算法·leetcode
惜.己1 小时前
针对nvm不能导致npm和node生效的解决办法
前端·npm·node.js