IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> 2021-08-31 -> 正文阅读

[JavaScript知识库]2021-08-31

使用elementui上传组件实现同一个页面上传不同类型的图片和视频

1.把upload组件抽离出去,在弹窗父组件引用子组件数据 addForm.vue代码如下:

<template>
 <div class="drawer-form">
   <el-drawer
      title=""
      :visible.sync="editrVisible"
      :modal="false"
      :with-header="false"
      v-loading="loading"
    >
<div class="upload-content">
  <div class="imgBox">
   <my-upload ref="upload1" :type="types[0]" :typeTitle="imgData[0].typeTitle" :resData.sync="resData1" :uploading.sync="uploading1"/>
 </div>
<div class="imgBox">
  <my-upload ref="upload2" :type="types[1]" :typeTitle="imgData[1].typeTitle" :resData.sync="resData2" :uploading.sync="uploading2"/>
  </div>
 <div class="imgBox">
   <my-upload ref="upload3" :type="types[2]" :typeTitle="imgData[2].typeTitle" :resData.sync="resData3" :uploading.sync="uploading3"/>
 </div>
</div>
<div class="drawer_colse" @click="cancelForm">
  <i class="el-icon-close"></i>
</div>
<div class="drawer__footer">
 <el-button size="mini" @click="onsubmit">确认</el-button>
 <el-button size="mini" @click="cancelForm">取消</el-button>
</div>
</el-drawer>
 </div>
</template>
<script>
import MyUpload from './myUpload';
export default {
  components: {
    MyUpload
  },
  data(){
  return {
  	type:0,//上传图片的类型,默认上传到第一个
    types:[0,1,2,3],
    uploading1:false,//是否有东西上传
    uploading2:false,//是否有东西上传
    uploading3:false,//是否有东西上传
    resData1:[],//图片类型一
    resData2:[],//视频录像
    resData3:[],//图片类型二
    imgData: [
        {typeTitle:'占道图片1'},
        {typeTitle:'视频录像'},
        {typeTitle:'占道图片2'},
      ], //图片列表
    imgList:[],//用于存储表格最后提交的数据
  }
 },
 methods: {
 //取消或关闭页面的时候需要清空的数据
 cancelForm() {
 	this.loading = false
    this.editrVisible = false;
    this.$refs.upload1.clearData()//清空已上传的数组列表
    this.$refs.upload2.clearData()
    this.$refs.upload3.clearData()
    this.uploading1 = false//恢复初始值
    this.uploading2 = false//恢复初始值
    this.uploading3 = false//恢复初始值
    this.imgList = [] //清空上传之后的数据
    },
onsubmit(formName) {  if(this.uploading1||this.uploading2||this.uploading3){
         this.$message({
          showClose: true,
          message: '当前有文件正在上传,请稍后',
          type: "warning",
            });
      }else{//没东西要上传或已经上传完
       this.loading = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
        //请求的方法
          this.addUpload(formName);
        } else {
          this.loading = false
          return false;
        }
      });
      }
    },
    addUpload(formName) {
      let newArr = []
      newArr = newArr.concat(this.resData1,this.resData2,this.resData3)
     newArr.forEach((v,i) =>{
        v.response.data.fileList.forEach((a,i) =>{
        //拿到自己想要的数据传给后台
          this.imgList.push(a)
        })
        })
      let pams = {
        ...this.newform,
        imgList:this.imgList
      };
      this.saveUpload(pams)
        .then((res) => {
          // console.log("新增上传", res);
          if (res.code === 1) {
            this.$message({
              showClose: true,
              message: "上传添加成功",
              type: "success",
            });
            this.$refs[formName].resetFields();
            //新增成功,刷新表格数据
            this.$parent.getList();
            this.cancelForm()
          } else{
            this.$message({
              showClose: true,
              message: `${res.msg}`,
              type: "warning",
            });
            this.cancelForm();
          }
        })
        .catch((err) => {});
    },
} 
}
</script>

2.抽离出来的上传组件myUpload.vue如下:

<template>
  <div class="imgBox-min">
    <el-upload
      ref="upload"
      class="upload-demo"
      :action="uploadAction"
      :headers="uploadHeader"
      :on-change="handleChange"
      :data="uploadData"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :on-error="handleImageError"
      :file-list="fileList"
      :show-file-list="true"
      :multiple="true"
      :before-upload="beforeUploadPicVideo"
      :auto-upload="true"
    >
      <slot>
        <div class="titip">
          <span>{{ typeTitle }}</span>
          <el-button class="upBtn" size="mini" icon="el-icon-upload" plain
            >上传文件</el-button
          >
        </div>
        <div
          v-if="this.fileList.length <= 0"
          class="el-upload__text">暂无数据
        </div>
      </slot>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  name: "",
  props: {
    uploading: {
      type: Boolean,
      default: false,
    },
    type: {
      type: Number,
      default: 0,
    },
    typeTitle: {
      type: String,
      default: "",
    },
    resData: {
      type: Array,
      default: [],
    },
    fileType: {
      type: String,
      default: "image",
    },
  },
  data() {
    const token = getToken();
    return {
      uploadAction: "https://jsonplaceholder.typicode.com/posts/",//上传的路径地址
      uploadHeader: {
        "Access-Token": token,
      },
      fileList: [],
    };
  },
  computed: {
    isUploading: {
      get() {
        return this.uploading;
      },
      set(val) {
        this.$emit("update:uploading", val);
      },
    },
    successData: {
      get() {
        return this.resData;
      },
      set(val) {
        this.$emit("update:resData", val);
      },
    },
    //获取父组件传过来的类型,传给后台识别是哪个类型
    uploadData: {
      get() {
        return { type: this.type };
      },
    },
  },
  watch: {},
  methods: {
  //清空数据
    clearData() {
      this.$refs.upload.clearFiles();
      this.successData = []
    },
    handleChange(file, fileList) {
      // 上传状态"uploading" ,"ready","success",'fail'
      let status = false
      for(var i = 0; i < this.$refs.upload.uploadFiles.length;i++){
        if(this.$refs.upload.uploadFiles[i].status === 'ready' || this.$refs.upload.uploadFiles[i].status === 'uploading'){
         status = true; //上传中 
         break;
        }
      }
      this.isUploading = status
      this.fileList = fileList;
    },
    beforeUploadPicVideo(file) {
      const typeAll = file.type.split("/");
      if (this.type === 1 && typeAll[0] != "video") {
        this.$message.error("此框应上传MP4视频格式");
        return false;
      }
      if(this.type != 1 && typeAll[0] != "image"){
        this.$message.error("该内容应上传图片");
        return false;
      }
      if (typeAll[0] === "video") {
        //视频
        const isLt100M = file.size / 1024 / 1024 < 100;
        // if (['video/mp4', 'video/ogg', 'video/flv','video/avi','video/wmv','video/rmvb'].indexOf(file.type) == -1) {
        if (["video/mp4"].indexOf(file.type) == -1) {
          this.$message.error("暂时仅支持上传MP4视频格式");
          return false;
        }
        if (!isLt100M) {
          this.$message.error("上传视频大小不能超过100M哦!");
          return false;
        }
      } else {
        //图片
        // const isAccept = 'image/jpeg' || 'image/jpg' || 'image/png' || 'image/gif'
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (
          [
            "image/jpeg",
            "image/jpg",
            "image/png",
            "image/gif",
          ].indexOf(file.type) === -1
        ) {
          this.$message.error(
            "上传图片只能是png、jpg、jpeg、gif格式的图片!"
          );
          return false;
        }
        if (!isLt10M) {
          this.$message.error("上传图片的大小不能超过10M");
          return false;
        }
      }
    },
    handleRemove(file, fileList) {
    //取消正在上传的文件时,调用handleChange方法,把参数传过去,让它重新计算
      this.handleChange(file,fileList)
      this.successData = fileList;
    },
    handleSuccess(res, file, fileList) {
      let self = this;
      if (res.code === 1) {
        self.successData = fileList;
        this.$message({
          showClose: true,
          message: `${res.msg}`,
          type: "success",
        });
      } else {
        this.$message({
          showClose: true,
          message: `${res.msg}`,
          type: "error",
        });
      }
    },
    handleImageError(err, file, fileList) {},
    beforeRemove(file, fileList) {
    //如果上传的框内容不是对应的图片或视频类型,不出现弹窗,直接删除数据
      if (this.type == 1 && ["video/mp4"].indexOf(file.raw.type) == -1) {
        return true;
      }
      if (
        this.type != 1 &&
        [
          "image/jpeg",
          "image/jpg",
          "image/png",
          "image/gif",
        ].indexOf(file.raw.type) == -1
      ) {
        return true;
      }
      return this.$confirm(`确定移除 ${file.name}`);
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2021-09-01 11:49:53  更:2021-09-01 11:50:10 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年6日历 -2024/6/18 8:01:46-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码