Vue 在使用v-if的前提下,使用elementResizeDetector配合ref获取元素块的高度

前言

公司的项目主要以Vue + elementUI为主,最近公司项目需要做一个附件上传的组件,如下图,然而在做的过程中,遇到了一定的问题。在缩小浏览器时,备注部分与附件查看处的滚动条重合了,这就使得滚动条无法使用。
在这个情况下,我就想到,对备注部分的元素块note进行监听。因为缩小浏览器窗口,会使得note部分的width减少(设置为自动占比100%),而在内容不变的情况下,势必会使该元素块的高度height增加。于是我就使用了elementResizeDetector对DOM进行监听。

Vue 在使用v-if的前提下,使用elementResizeDetector配合ref获取元素块的高度_第1张图片
Vue 在使用v-if的前提下,使用elementResizeDetector配合ref获取元素块的高度_第2张图片
核心代码

      const _this = this;
      const erd = elementResizeDetector();
      erd.listenTo(document.getElementById("app"), element => {
     
        _this.$nextTick(() => {
     
          //监听到事件后执行的业务逻辑
          this.noteHeightNow = _this.$refs.noteHeight.offsetHeight
        });
      });

遇到的问题

1. 在computed中没法操作dom元素,比如

computed: {
	w() {
		return  this.$refs.box.offsetWidth
	}
}

运行中报undefined错误,后来改成在mounted中获取this.$refs.box.offsetWidth,后来发现,在computed中,DOM元素未加载下来,保险起见,还是在mounted操作DOM

2.vue使用this.$refs.xx在mounted中获取DOM元素为undefined

如果在 DOM 结构中的某个 DOM 节点使用了 v-if、v-show 或者 v-for(即根据获取到的后台数据来动态操作 DOM,即响应式),那么这些 DOM 是不会在 mounted 阶段找到的。

mounted 阶段,一般是用于发起后端请求,获取数据,配合路由钩子做一些事情。简单来说就是在 mounted 钩子中加载数据而已,加载回来的数据是不会在这个阶段更新到 DOM 中的。所以在 mounted 钩子中使用 $refs,如果 ref 是定位在有 v-if、v-for、v-show 的 DOM 节点中,返回来的只能是 undefined,因为在 mounted 阶段他们根本不存在。

如果说 mounted 阶段是加载阶段,那么 updated 阶段则是完成了数据更新到 DOM 的阶段(对加载回来的数据进行处理),此时,再使用 this.$refs.xx,就 100% 能找到该 DOM 节点。

updated 与 mounted 不同的是,在每一次的 DOM 结构更新,Vue.js 都会调用一次 updated 钩子函数!而 mounted 钩子函数仅仅只执行一次而已。

Vue 在使用v-if的前提下,使用elementResizeDetector配合ref获取元素块的高度_第3张图片

最终方案

在watch里面监听数据变化,在v-if 的值为 true的时候,调用监听方法

  watch: {
    website(value) {
      if (this.note !== '') {
        this.onWatch()
      }
    }
  },
  methods: {
    onWatch() {
      const _this = this;
      const erd = elementResizeDetector();
      erd.listenTo(document.getElementById("app"), element => {
        _this.$nextTick(() => {
          //监听到事件后执行的业务逻辑
          this.noteHeightNow = _this.$refs.noteHeight.offsetHeight
        });
      });
    },
   }	

附件上传组件

<template>
  <div class="attachment-wrp">
    <el-row :gutter="20">
      <el-col :span="9">
        <div class="view-left">
          <!-- margin-bottom:20px -->
          <el-card shadow="never" style=" height: 60%;" body-style="padding:0">
            <div slot="header">
              <span style="float: left;"
                ><img src="/static/img/mainTable_icon.png" />附件</span
              >
              <!-- <span style="font-size:14px;font-weight:bold;">附件</span> -->
              <el-button @click="del" type="text" :disabled="showFlag"
                >删除</el-button
              >
              <el-button @click="setPicture" type="text" :disabled="showFlag"
                >设为首页图片</el-button
              >
            </div>
            <slot name="searchCard">
              <publicTable
                columnSelection
                :columns="headTable"
                :data="attachmentData"
                :loading="loading"
                :initHeight="tableHeight"
                @rowClick="rowClick"
                @selectionChange="select"
              ></publicTable>
            </slot>
          </el-card>
          <el-card shadow="never" class="accessoryBox">
            <div slot="header">
              <span style="float: left;"
                ><img src="/static/img/mainTable_icon.png" />上传附件</span
              >
            </div>
            <slot name="mainBody">
              <el-form
                :inline="false"
                :model="uploadData"
                :rules="rules"
                label-width="90px"
                ref="ruleForm"
              >
                <el-form-item label="附件类型:" prop="fileType">
                  <el-select
                    v-model="uploadData.fileType"
                    placeholder="请选择"
                    :disabled="showFlag"
                    style="width:100%;"
                  >
                    <el-option
                      v-for="(item, index) in options"
                      :key="index"
                      :label="item.dictName"
                      :value="item.dictValue"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="附件路径:" prop="filePath">
                  <el-input
                    style="width:calc(100% - 50px);"
                    v-model="uploadData.filePath"
                    clearable
                    disabled
                  ></el-input>
                  <el-upload
                    class="upload-demo from"
                    ref="upload"
                    :disabled="showFlag"
                    :action="uploadUrl"
                    accept=".xls,.xlsx,.txt,.png,.docx,.doc,.pdf,.jpg,.PDF"
                    :auto-upload="false"
                    :file-list="fileList"
                    :on-change="handleChange"
                    :limit="2"
                    :on-success="uploadSuccess"
                    :show-file-list="false"
                  >
                    <el-button
                      slot="trigger"
                      size="small"
                      type="primary"
                      :disabled="showFlag"
                      class="el-icon-more"
                    ></el-button>
                  </el-upload>
                </el-form-item>
                <el-form-item label="附件名称:" prop="fileName">
                  <el-input
                    v-model="uploadData.fileName"
                    clearable
                    placeholder="附件名称"
                    :disabled="showFlag"
                    style="width:100%;"
                  ></el-input>
                </el-form-item>
                <el-form-item label="附件描述:">
                  <el-input
                    style="width:100%;"
                    v-model="uploadData.describe"
                    clearable
                    type="textarea"
                    :disabled="showFlag"
                    :maxlength="50"
                    placeholder="附件描述"
                  ></el-input>
                </el-form-item>
              </el-form>
              <!-- <el-upload class="upload-demo from"
                         ref="upload"
                         :disabled="showFlag"
                         :action="uploadUrl"
                         :auto-upload="false"
                         :file-list="fileList"
                         :on-change="handleChange"
                         :limit="2"
                         :on-success="uploadSuccess"
                         :show-file-list="false">
                <!-:show-file-list="false" -->
              <div style="text-align: right;">
                <el-button @click="clear" size="small" :disabled="showFlag"
                  >重置</el-button
                >
                <el-button
                  style="margin-left: 10px;"
                  size="small"
                  type="primary"
                  :loading="isUploadLoading"
                  :disabled="showFlag"
                  @click="submitUpload('ruleForm')"
                  >上传</el-button
                >
              </div>
              <!-- </el-upload> -->
            </slot>
          </el-card>
        </div>
      </el-col>
      <el-col :span="15">
        <div class="view-right">
          <el-card shadow="never">
            <div slot="header" class="clearfix">
              <span style="float: left;"
                ><img src="/static/img/mainTable_icon.png" />附件查看</span
              >
            </div>
            <div
              v-loading="viewLoading"
              element-loading-text="加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="#fff"
            >
              <div
                class="fileview"
                :style="{ height: imgHeight + 'px' }"
                v-if="website !== ''"
              >
                <img :src="website" v-if="filteViewType === 0" />
                <div v-else-if="filteViewType === 1">
                  <iframe :src="website" class="iframe"></iframe>
                </div>
                <div
                  v-else-if="filteViewType === 2"
                  class="webBox"
                  :style="{ 'margin-bottom': note !== '' ? ((noteHeightNow + 22) + 'px') : '0px' }"
                >
                  <div v-html="website" style="padding: 10px;"></div>
                </div>
                <div v-else-if="filteViewType === 99" class="not-suport">
                  <!--{
     {
     filename}}-->
                  <!--<div> <svg-icon :icon-class="getIcon(filename)"></svg-icon></div>-->
                  <div class="desc">
                    不支持的预览格式
                  </div>
                </div>
                <div class="note" v-if="note !== ''" ref="noteHeight">备注: {
     {
      note }}</div>
              </div>
              <div
                class="no_data"
                :style="{ height: imgHeight + 'px' }"
                v-if="website === ''"
              >
                <img
                  style="width: 30%;height: 35%;"
                  src="/static/img/no_acc.png"
                  alt=""
                />
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
     
  autoSaveFile,
  downloadFileURl,
  viewFile,
  view
} from "@/api/admin/document/document.js";
import {
     
  getAttachmentList,
  addAttachment,
  addReportAttachment,
  addProjectAttachment,
  delAttachment,
  delMonthAttachment,
  setFirstPage,
  getBatchAttachmentList,
  addBatchAttachment
} from "@/api/g3Asset/attachment";
import {
      getToken, getClientToken } from "@/utils/auth";
import elementResizeDetector from 'element-resize-detector'
import publicTable from "@/components/publicTable";
import {
      Time, myTrim } from "@/utils/index";
export default {
     
  name: "enclosure", // 附件
  components: {
      publicTable },
  props: {
     
    name: {
     
      type: String,
      default: ""
    },
    activityId: {
     
      type: String,
      default: ""
    },
    activityIdName: {
     
      type: String,
      default: ""
    },
    type: {
     
      type: String,
      default: ""
    }
  },
  watch: {
     
    website(value) {
     
      if (this.note !== '') {
     
        this.onWatch()
      }
    }
  },
  data() {
     
    var validateFileName = (rule, value, callback) => {
     
      if (!myTrim(value)) {
     
        return callback(new Error("请输入附件名称"));
      } else {
     
        return callback();
      }
    };
    return {
     
      filteViewType: 0,
      bizOwnerId: "",
      showFlag: false,
      headTable: [
        {
     
          label: "节点",
          prop: "activityIdName",
          width: this.constant.activityIdNameWidth,
          align: "center"
        },
        {
     
          label: "类型",
          prop: "fileType",
          width: this.constant.valueTypeWidth,
          align: "center",
          formatter: this.fileTypeFormatter
        },
        {
     
          label: "名称",
          prop: "fileName",
          width: this.constant.nameWidth,
          align: "center"
        },
        {
     
          label: "上传人",
          prop: "uploadUser",
          width: this.constant.useUserNameWidth,
          align: "center"
        },
        {
     
          label: "上传时间",
          prop: "uploadTime",
          width: this.constant.distributeDateWidth,
          align: "center",
          formatter: this.updateTimeFormatter
        }
      ],
      rules: {
     
        fileType: [
          {
      required: true, message: "请选择附件类型", trigger: "change" }
        ],
        fileName: [
          {
     
            required: true,
            message: "请输入附件名称",
            trigger: "blur",
            validator: validateFileName
          }
        ],
        filePath: [
          {
      required: true, message: "请选择附件路径", trigger: "blur" }
        ]
      },
      parentFileId: "file123456789", // 根文件夹id
      options: [],
      // value: '',
      uploadData: {
      filePath: "", fileName: "", fileType: "", describe: "" },
      batchObj: {
     },
      fileList: [],
      attachmentData: [],
      selectList: [],
      loading: false, // 表格加载
      isUploadLoading: false, // 上传加载
      website: "", // 预览路径
      isImg: false,
      imgUrl: "",
      viewLoading: false, // 预览加载
      note: "",
      noteHeightNow: '',
      CurrBizCode: "" // 当前的业务编码
      // fileList: [{ name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }, { name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }]
    };
  },
  computed: {
     
    uploadUrl() {
     
      return (
        process.env.VUE_APP_BASE_API +
        autoSaveFile() +
        "?" +
        process.env.VUE_APP_USER_TOKEN_PARAM +
        "=" +
        getToken() +
        "&" +
        process.env.VUE_APP_CLIENT_TOKEN_PARAM +
        "=" +
        getClientToken() +
        "&parent_file_id=" +
        this.parentFileId
      );
    },
    imgHeight() {
     
      // 动态计算高度
      // return this.documentClientHeight - 166
      return this.mianViewHeight("enclosure-picture");
      // return this.documentClientHeight - 170 <= 407 && this.documentClientHeight - 170 > 0 ? 407 : this.documentClientHeight - 170
    },
    tableHeight() {
     
      return this.mianViewHeight("enclosure-form");
      // return this.documentClientHeight - 491 <= this.constant.minListHeight && this.documentClientHeight - 491 > 0 ? this.constant.minListHeight : this.documentClientHeight - 491
    },
  },
  created() {
     },
  mounted() {
     
  },
  methods: {
     
    onWatch() {
     
      const _this = this;
      const erd = elementResizeDetector();
      erd.listenTo(document.getElementById("app"), element => {
     
        _this.$nextTick(() => {
     
          //监听到事件后执行的业务逻辑
          this.noteHeightNow = _this.$refs.noteHeight.offsetHeight
        });
      });
    },
    // 清空当前的业务编码
    cleanCurrBizCode() {
     
      this.CurrBizCode = "";
    },
    // 获取当前的业务编码
    getCurrBizCode(code) {
     
      // 取到当前页面传参的业务编码
      this.CurrBizCode = code;
    },
    clear() {
     
      this.uploadData = Object.assign(this.uploadData, {
     
        filePath: "",
        fileName: "",
        fileType: "",
        describe: ""
      });
    },
    init(bizid, type, obj) {
     
      this.bizOwnerId = bizid;
      this.isUploadLoading = false;
      this.uploadData = {
     
        filePath: "",
        fileName: "",
        fileType: "",
        describe: ""
      };
      this.imgUrl = "";
      this.website = "";
      if (this.$refs["ruleForm"]) {
     
        this.$refs["ruleForm"].resetFields();
      }
      this.$store.dispatch("getDictionaryList", "FILE_TYPE").then(res => {
     
        // 获取附件类型列表
        // res.map(v => {
     
        //   this.options.push({ value: v.dictValue, label: v.dictName })
        // })
        this.options = res;
      });
      if (!type) {
     
        this.getFileList();
        return false;
      }
      if (type === "batch") {
     
        this.type = "batch";
        this.batchObj = obj;
        this.getBatchFileList();
      } else {
     
        this.type = type;
        this.getFileList();
      }
    },
    getFileList() {
     
      // 获取附件列表
      this.loading = true;
      getAttachmentList({
      bizOwnerId: this.bizOwnerId }).then(res => {
     
        if (res.data.code === this.globalConstant.success) {
     
          this.attachmentData = res.data.data;
          this.loading = false;
        } else {
     
          this.$message.error(res.data.msg);
        }
      });
    },
    getBatchFileList() {
     
      // 按批显示获取附件列表
      this.loading = true;
      const params = {
     
        financialStatus: this.batchObj.financialStatus,
        batchCode: this.batchObj.batchCode,
        bizid: this.bizOwnerId,
        rgId:
          this.$store.getters.belong_org.code ||
          this.$store.getters.userInfo.orgId
      };
      getBatchAttachmentList(params).then(res => {
     
        if (res.data.code === this.globalConstant.success) {
     
          this.attachmentData = res.data.data;
          this.loading = false;
        } else {
     
          this.$message.error(res.data.msg);
        }
      });
    },
    rowClick(row, list) {
     
      // 单行点击
      if (row.fileComment) {
     
        this.note = row.fileComment;
      } else {
     
        this.note = "";
      }
      // 先判断是否可以预览,去下载文件,展示
      this.viewLoading = true;
      // 判断是 否是图片
      const ext = row.documentType;
      // console.log('附件类型==' + ext)
      // const ext = this.fileViewProps.file_path.substr((this.fileViewProps.file_path.lastIndexOf('.') + 1), this.fileViewProps.file_path.length).toLowerCase()
      switch (ext) {
     
        case "webp":
        case "WMF":
        case "raw":
        case "ai":
        case "eps":
        case "ufo":
        case "dxf":
        case "pcd":
        case "cdr":
        case "psd":
        case "svg":
        case "fpx":
        case "exif":
        case "tga":
        case "pcx":
        case "gif":
        case "tiff":
        case "bmp":
        case "jpg":
        case "jpeg":
        case "png":
          this.filteViewType = 0;
          this.website =
            process.env.VUE_APP_BASE_API +
            downloadFileURl(row.fileId) +
            "?" +
            process.env.VUE_APP_USER_TOKEN_PARAM +
            "=" +
            getToken() +
            "&" +
            process.env.VUE_APP_CLIENT_TOKEN_PARAM +
            "=" +
            getClientToken();
          this.viewLoading = false;
          break;
        case "xls":
        case "xlsx":
        case "doc":
          // case 'docx':
          view({
      id: row.fileId })
            .then(res => {
     
              if (res.data.code === "9999") {
     
                if (/(doc|docx)$/.test(ext)) {
     
                  this.filteViewType = 1;
                  // process.env.VUE_APP_BASE_API + process.env.VUE_APP_ADMIN_API + '/' +
                  this.website =
                    process.env.VUE_APP_BASE_API +
                    process.env.VUE_APP_ADMIN_API +
                    "/" +
                    res.data.attributes.html +
                    "?" +
                    process.env.VUE_APP_USER_TOKEN_PARAM +
                    "=" +
                    getToken() +
                    "&" +
                    process.env.VUE_APP_CLIENT_TOKEN_PARAM +
                    "=" +
                    getClientToken();
                } else {
     
                  this.filteViewType = 2;
                  this.website = res.data.attributes.html;
                }
                this.viewLoading = false;
              } else {
     
                this.$message({
     
                  type: "warning",
                  message: res.data.msg
                });
                this.viewLoading = false;
                // loading.close()
              }
            })
            .catch(() => {
     
              this.viewLoading = false;
              this.$message({
     
                type: "error",
                message: "服务器错误,请联系管理员"
              });
              // loading.close()
            });
          break;
        case "pdf":
          viewFile({
      id: row.fileId })
            .then(res => {
     
              if (res.data.code === "9999") {
     
                const files = this.dataURLtoFile(
                  res.data.attributes.base64String,
                  row.fileName
                );
                const fileUrl = this.getObjectURL(files);
                this.website =
                  "../../../../../../public/static/pdf/web/viewer.html?file=" +
                  fileUrl;
                this.filteViewType = 1;
                this.viewLoading = false;
              } else {
     
                this.$message({
     
                  type: "warning",
                  message: res.data.msg
                });
                this.viewLoading = false;
              }
            })
            .catch(() => {
     
              this.$message({
     
                type: "error",
                message: "服务器错误,请联系管理员"
              });
              this.viewLoading = false;
              // loading.close()
            });
          break;
        default:
          this.filteViewType = 99;
          this.viewLoading = false;
      }
    },
    select(list, data) {
     
      // 行单选中
      this.selectList = list;
    },
    submitUpload(formName) {
     
      // 上传
      this.$refs[formName].validate(valid => {
     
        if (valid) {
     
          if (this.type === "batch") {
     
            if (this.batchObj.batchcode === "") {
     
              this.$message.error("请先保存单据");
              return false;
            }
          } else if (this.type === "project") {
     
            if (this.bizOwnerId === "") {
     
              this.$message.error("请选择工程");
              return false;
            }
          } else {
     
            if (this.bizOwnerId === "") {
     
              this.$message.error("请先保存单据");
              return false;
            }
          }
          this.isUploadLoading = true;
          this.$refs.upload.submit();
        } else {
     
          return false;
        }
      });
    },
    setPicture() {
     
      // 设为首页图片
      // 判断是不是超过选中超过1个
      // 判断文件类型是不是图片类型
      if (this.selectList.length <= 0) {
     
        this.$message.error("请选择需要设置的附件");
        return;
      }
      if (this.selectList.length > 1) {
     
        this.$message.error("请选择单个附件");
        return;
      }
      // var strFilter = 'jpeg|gif|jpg|png|bmp|pic|'
      var strFilterList = ["jpeg", "gif", "jpg", "png", "bmp", "pic"];
      // console.log(strFilter.indexOf(this.selectList[0].documentType))
      if (strFilterList.indexOf(this.selectList[0].documentType) === -1) {
     
        this.$message.error("非图片类型,不能设置为首页");
        return;
      }
      // 请求设置首页接口
      var requestData = {
     
        bizid: this.selectList[0].bizid,
        bizOwnerId: this.selectList[0].bizOwnerId
      };
      setFirstPage(requestData).then(res => {
     
        if (res.data.code === this.globalConstant.success) {
     
          this.getFileList();
          this.$message.success("设置成功");
          this.$emit("resetImage");
        } else {
     
          this.$message.error(res.data.msg);
        }
      });
    },
    del() {
     
      // 删除
      if (this.selectList.length <= 0) {
     
        this.$message.error("请选择需要删除的附件");
        return;
      }
      var requestData = {
     
        fileId: "",
        bizOwnerId: this.bizOwnerId,
        tableName: this.name,
        roleNo: this.$store.getters.current_role.roleNo,
        zcgljb: this.$store.getters.mgtLevel
      };
      this.selectList.map(v => {
     
        if (requestData.fileId === "") {
     
          requestData.fileId = v.fileId;
        } else {
     
          requestData.fileId = requestData.fileId + "," + v.fileId;
        }
      });
      if (this.type === "month") {
     
        delAttachment(requestData).then(res => {
     
          if (res.data.code === this.globalConstant.success) {
     
            this.getFileList();
            this.$message.success("删除成功");
            this.website = "";
            this.imgUrl = "";
            this.$emit("deleteSuccess");
            this.$emit("reloadImg");
          } else {
     
            this.$message.error(res.data.msg);
          }
        });
      } else {
     
        delMonthAttachment(requestData).then(res => {
     
          if (res.data.code === this.globalConstant.success) {
     
            this.getFileList();
            this.$message.success("删除成功");
            this.$emit("deleteSuccess");
            this.website = "";
            this.imgUrl = "";
            this.$emit("reloadImg");
          } else {
     
            this.$message.error(res.data.msg);
          }
        });
      }
    },
    handleChange(file, fileList) {
     
      // 选取本地文件
      if (fileList.length === 0) {
     
        return;
      }
      this.fileList = fileList;
      if (this.fileList.length > 1) {
     
        this.fileList.shift();
      }
      if (file.name.indexOf(".") < 0) {
     
        this.uploadData.fileName = file.name;
        this.uploadData.documentType = "";
      } else {
     
        this.uploadData.fileName = file.name.substring(
          0,
          file.name.indexOf(".")
        );
        this.uploadData.documentType = file.name
          .split(".")
          .pop()
          .toLowerCase();
      }
      this.uploadData.filePath = file.name;
    },
    uploadSuccess(res, file, fileList) {
     
      // 上传文件成功
      if (res.code === "9999" && res.success) {
     
        if (this.type === "batch") {
     
          const postVal = {
     
            bizCode: this.CurrBizCode,
            rgId:
              this.$store.getters.belong_org.code ||
              this.$store.getters.userInfo.orgId,
            fileId: res.obj,
            fileName: this.uploadData.fileName,
            financialStatus: this.batchObj.financialStatus,
            documentType: this.uploadData.documentType,
            batchcode: this.batchObj.batchcode,
            fileType: parseInt(this.uploadData.fileType),
            tableName: this.name,
            batchCode: this.batchObj.batchCode,
            bizid: this.bizOwnerId,
            roleNo: this.$store.getters.current_role.roleNo,
            zcgljb: this.$store.getters.mgtLevel
          };
          addBatchAttachment(postVal).then(res => {
     
            // todo:请求附件列表接口,刷新列表,取消所有选中
            if (res.data.code === this.globalConstant.success) {
     
              this.attachmentData = res.data.data;
              this.isUploadLoading = false;
              this.$message.success("上传成功");
              this.$emit("uploadSuccess");
              // 重置form表单
              this.$refs.ruleForm.resetFields();
              this.$set(this.uploadData, "describe", "");
              this.getBatchFileList();
              this.$emit("reloadImg");
            } else {
     
              this.$message.error(res.data.msg);
              this.clear();
              this.isUploadLoading = false;
            }
          });
        } else if (this.type === "project") {
     
          const postVal = {
     
            bizCode: this.CurrBizCode,
            fileId: res.obj,
            rgId:
              this.$store.getters.belong_org.code ||
              this.$store.getters.userInfo.orgId,
            fileName: this.uploadData.fileName,
            fileType: parseInt(this.uploadData.fileType),
            documentType: this.uploadData.documentType,
            activityId: this.activityId,
            activityIdName: this.activityIdName,
            bizOwnerId: this.bizOwnerId,
            fileComment: this.uploadData.describe,
            tableName: this.name,
            roleNo: this.$store.getters.current_role.roleNo,
            zcgljb: this.$store.getters.mgtLevel
          };
          addProjectAttachment(postVal).then(res => {
     
            // todo:请求附件列表接口,刷新列表,取消所有选中
            if (res.data.code === this.globalConstant.success) {
     
              this.attachmentData = res.data.data;
              this.isUploadLoading = false;
              this.$message.success("上传成功");
              this.$emit("uploadSuccess");
              // 重置form表单
              this.$refs.ruleForm.resetFields();
              this.$set(this.uploadData, "describe", "");
              this.getFileList();
              this.$emit("reloadImg");
            } else {
     
              this.$message.error(res.data.msg);
              this.clear();
              this.isUploadLoading = false;
            }
          });
        } else if (this.type === "report") {
     
          const postVal = {
     
            bizCode: this.CurrBizCode,
            fileId: res.obj,
            rgId:
              this.$store.getters.belong_org.code ||
              this.$store.getters.userInfo.orgId,
            fileName: this.uploadData.fileName,
            fileType: parseInt(this.uploadData.fileType),
            documentType: this.uploadData.documentType,
            activityId: this.activityId,
            activityIdName: this.activityIdName,
            bizOwnerId: this.bizOwnerId,
            fileComment: this.uploadData.describe,
            tableName: this.name,
            roleNo: this.$store.getters.current_role.roleNo,
            zcgljb: this.$store.getters.mgtLevel
          };
          addReportAttachment(postVal).then(res => {
     
            // todo:请求附件列表接口,刷新列表,取消所有选中
            if (res.data.code === this.globalConstant.success) {
     
              this.attachmentData = res.data.data;
              this.isUploadLoading = false;
              this.$message.success("上传成功");
              this.$emit("uploadSuccess");
              // 重置form表单
              this.$refs.ruleForm.resetFields();
              this.$set(this.uploadData, "describe", "");
              this.getFileList();
              this.$emit("reloadImg");
            } else {
     
              this.$message.error(res.data.msg);
              this.clear();
              this.isUploadLoading = false;
            }
          });
        } else {
     
          const postVal = {
     
            bizCode: this.CurrBizCode,
            fileId: res.obj,
            rgId:
              this.$store.getters.belong_org.code ||
              this.$store.getters.userInfo.orgId,
            fileName: this.uploadData.fileName,
            fileType: parseInt(this.uploadData.fileType),
            documentType: this.uploadData.documentType,
            activityId: this.activityId,
            activityIdName: this.activityIdName,
            bizOwnerId: this.bizOwnerId,
            fileComment: this.uploadData.describe,
            tableName: this.name,
            roleNo: this.$store.getters.current_role.roleNo,
            zcgljb: this.$store.getters.mgtLevel
          };
          addAttachment(postVal).then(res => {
     
            // todo:请求附件列表接口,刷新列表,取消所有选中
            if (res.data.code === this.globalConstant.success) {
     
              this.attachmentData = res.data.data;
              this.isUploadLoading = false;
              this.$message.success("上传成功");
              this.$emit("uploadSuccess");
              // 重置form表单
              this.$refs.ruleForm.resetFields();
              this.$set(this.uploadData, "describe", "");
              this.getFileList();
              this.$emit("reloadImg");
            } else {
     
              this.$message.error(res.data.msg);
              this.clear();
              this.isUploadLoading = false;
            }
          });
        }
      } else {
     
        this.$message.error("上传失败");
      }
    },
    fileTypeFormatter(row, comu, val) {
     
      // 文件类型格式化
      return this.options
        .filter(e => e.dictValue + "" === val + "")
        .map(j => j.dictName);
    },
    updateTimeFormatter(row, comu, val) {
     
      // 日期格式化
      return Time(val);
    },
    // 查看情况下按钮不可点
    hideBtn() {
     
      this.showFlag = true;
    },
    showBtn() {
     
      this.showFlag = false;
    },
    getObjectURL(file) {
     
      let url = null;
      if (window.createObjectURL !== undefined) {
     
        // basic
        url = window.createObjectURL(file);
      } else if (window.webkitURL !== undefined) {
     
        // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
      } else if (window.URL !== undefined) {
     
        // mozilla(firefox)
        url = window.URL.createObjectURL(file);
      }
      return url;
    },
    dataURLtoFile(dataurl, filename) {
     
      // 将base64转换为文件
      const arr = dataurl.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
     
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {
      type: mime });
    }
  }
};
</script>
<style lang="scss">
.attachment-wrp {
     
  .view-left {
     
    width: 100%;
    height: 100%;
    margin: 10px;
    .el-card__header {
     
      height: 40px;
      padding: 7px 10px;
      img {
     
        width: 18px;
        height: 18px;
        position: relative;
        top: 4px;
        margin-right: 5px;
      }
      .el-button {
     
        margin-top: 6px;
        float: left;
        padding: 0;
        margin-left: 10px;
      }
    }
  }
  .view-right {
     
    margin: 10px 10px 10px 0px;
    .el-card__header {
     
      height: 40px;
      padding: 7px 10px;
      img {
     
        width: 18px;
        height: 18px;
        position: relative;
        top: 4px;
        margin-right: 5px;
      }
      .el-button {
     
        margin-top: 6px;
        float: left;
        padding: 0;
        margin-left: 10px;
      }
    }
  }

  .from {
     
    display: inline-block;
    // display: flex;
    // justify-content: flex-end;
  }
  .accessoryBox {
     
    height: 48%;
    margin-top: 10px;
    overflow: auto;
    position: relative;
    // .tit {
     
    //   height: 36px;
    //   line-height: 36px;
    //   padding-left: 10px;
    //   margin-bottom: 10px;
    //   color: #666;
    //   font-size: 16px;
    //   border-bottom: 1px solid #ebeef5;
    //   text-align: left;
    // }
  }
  .fileview {
     
    width: 100%;
    // height: 680px;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    .webBox {
     
      max-width: 100%;
      max-height: 100%;
      overflow: auto;
    }
    img {
     
      display: block;
      margin: auto;
      max-height: 70%;
      max-width: 70%;
      width: auto;
      height: auto;
    }
    .note {
     
      position: absolute;
      width: 100%;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      text-align: center;
      padding: 0 5%;
      color: #363636;
      background-color: rgba(196, 194, 194, 0.5);
    }
  }
  .iframe {
     
    width: 100%;
    height: 100%;
  }
  .not-suport {
     
    position: absolute;
    font-size: 14px;
    color: #8f9298;
    top: 40%;
    left: 45%;
    line-height: 20px;
    .svg-icon {
     
      width: 50px !important;
      height: 50px !important;
    }
    .desc {
     
      margin-left: -20px;
    }
  }
  .no_data {
     
    width: 100%;
    // height: 680px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #eef4fa;
  }
}
</style>

你可能感兴趣的:(项目问题)