vue+element(项目中的使用)

Table

1,带选择的table,选择时选择对应的id进行操作

 let arr = [];  //选择id存放的数组
      for (let i = 0; i < val.length; i++) {
        arr.push(val[i].supervisonDocId);
        for (let j = 0; j < arr.legnth; j++) {
          if (arr[j] === val[i].supervisonDocId) {
            arr.splice(j, 1);
          }
        }
      }

点击单元格触发的事件

 官网tabble有事件的名称
 @cell-click="clickData"
 
  <template slot-scope="scope">
      <span v-for="(item, index) in scope.row.operation":key="index" @click.stop="choseC(scope.row,item.type)" >{{ item.name }}</span>
  </template>
  单元格项有不同的操作按钮使用 slot-scope="scope"
在el-table-column中 加入一个随机的key值,这样界面切换的时候检测到不同的key值就会重新去加载
:key="Math.random()"

2,自定义表头label

<template  slot="header"></template>

3,筛选

sortable
sortable="custom"  //自定义筛选
@sort-change="sortChange"
sortChange(column) {
  if (column.order == "descending") {
  }else{
  }
}  
居中
.el-table /deep/ .is-leaf {
  text-align: center;

}
.el-table /deep/ td {
  text-align: center;
}

2,表格没有数据时只显示表头(.el-table__empty-block:display:none)

From

1,校验数组
prop="file"
const validateMealPicture = (rule, value, callback) => {
  if (value.length > 0) {
    callback();
  } else {
    return callback(new Error("请至少上传一个图片"));
  }
};
   file: [ { type: "array",validator: validateMealPicture, required: true,}, ],
————————————————————
  清除校验
  this.$refs.******.clearValidate();

表格导出

1,导出整个表格–用id
xlsx 和 file-saver

js文件
import XLSX from "xlsx";
import FileSaver from "file-saver";

/**
 * @param id {String} 传入表格的id名称
 * @returns {File} 生成xlsx文件
 * 不要动函数结构,必须是es6语法
 */
const exportExcels = id => {
  var wb = XLSX.utils.table_to_book(document.querySelector("#" + id + ""));
  console.log(wb);
  var wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array"
  });
  let date = new Date();
  try {
    FileSaver.saveAs(
      new Blob([wbout], { type: "application/octet-stream" }),
      date.getTime() + ".xlsx"
    );
  } catch (e) {
    if (typeof console !== "undefined") console.log(e, wbout);
  }
  return wbout;
};
export default { exportExcels };
导入
import xlsx from "*****";
点击事件
 xlsx.exportExcels("*****");   //table的id

2,单条导出
js文件
(1):单页面使用

//item是一条的数据
    getExportList(item) {
      item.arr = "删除" + "," + "下载附件";
      item.Time = item.sTime + "~" + item.eTime;
//数据处理,可以根据数据情况来
      this.export2Excel(item);
    },
    export2Excel(item) {
      let list = [];
      list.push(item);
      require.ensure([], () => {
        const { export_json_to_excel } = require("../excel/Export2Excel");
        const tHeader = [   //表头
          "检查时间",
          "文件名称",
          "生成人员",
          "生成时间",
          "操作",
        ];
        const filterVal = [  //表头对应的字段
          "Time",
          "fileName",
          "createUser",
          "createTime",
          "arr",
        ];
        const data = this.formatJson(filterVal, list);    //list是这一条数据转为数组的格式
        export_json_to_excel(tHeader, data, "报告列表");
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },

(2):多页面使用

export function export2Excel(columns,list){
    require.ensure([], () => {
        const { export_json_to_excel } = require('./excel/Export2Excel');  //路径
        let tHeader = []
        let filterVal = []
        columns.forEach(item =>{
            tHeader.push(item.title)      //title,key  注意
            filterVal.push(item.key)
        })
        const data = list.map(v => filterVal.map(j => v[j]))
        export_json_to_excel(tHeader, data, '报告列表');
    })
}
引入
import { export2Excel } from "****文件名";

```bash
   getExportList(item) {
      item.arr = "删除" + "," + "下载附件";
      item.Time = item.sTime + "~" + item.eTime;
      //数据处理,可以根据数据情况来
      this.export2Excel(item);
    },
    export2Excel(item) {
      let arr = [
        { title: "检查时间", key: "Time" },
        { title: "文件名称", key: "fileName" },
        { title: "生成人员", key: "createUser" },
        { title: "生成时间", key: "arr" },              //title和key是封装方法里对应的
      ];
      let list = [];
      list.push(item);
      export2Excel(arr, list);      //arr是包括表头和表头对应的字段名的数组,list是单条数据的数组
    },

3,最终版(导出内容不挤在一起)
npm install xlsx --save
npm install file-saver --save
Export2Excel文件和blob文件

导出部分代码
const {export_json_to_excel, } = require("../../excel/Export2Excel.js"); //刚刚新建Export2Excel.js文件的路径
const tHeader = [ "",]; //自定义列名
const filterVal = [""]; //对应内容
const data = this.formatJson(filterVal, this.json_data);
export_json_to_excel(tHeader, data, "文件名"); //导出文件名称
----
formatJson(filterVal, jsonData) {  
	return jsonData.map((v) => filterVal.map((j) => v[j]));
},
表格合并列
:span-method="arraySpanMethod"
//数据处理
    flitterData(arr) {
      console.log(arr,111)
      let spanOneArr = []
      let spanTwoArr = []
      let concatOne = 0
      let concatTwo = 0
      arr.forEach((item, index) => {
        if (index === 0) {
          spanOneArr.push(1);
          spanTwoArr.push(1);
        } else {
          if (item.area === arr[index - 1].area) { //第一列需合并相同内容的判断条件 //字段判断area相同
            spanOneArr[concatOne] += 1;
            spanOneArr.push(0);
          } else {
            spanOneArr.push(1);
            concatOne = index;
          };
          if (item.area === arr[index - 1].area && item.numberOfArea === arr[index - 1].numberOfArea) {//第二列需合并相同内容的判断条件
            spanTwoArr[concatTwo] += 1;
            spanTwoArr.push(0);
          } else {
            spanTwoArr.push(1);
            concatTwo = index;
          };
        }
      });
      return {
        one: spanOneArr,
        two: spanTwoArr,
      }
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }){
    //合并2  3if (columnIndex === 2) {
          const _row = (this.flitterData(this.listData).one)[rowIndex];
          const _col = _row > 0 ? 1 : 0;
            return {
              rowspan: _row,
              colspan: _col
          };
         }
         if (columnIndex === 3) {
          const _row = (this.flitterData(this.listData).two)[rowIndex];
          const _col = _row > 0 ? 1 : 0;
            return {
              rowspan: _row,
              colspan: _col
            };
        }
    },

## Upload

```bash
两种方式
1,action带链接
 
 
2,
 
  const formData = new FormData();
    formData.append("file", file);
    this.$post(
      "sv/dictionary/uploadFile" + "?uuid=" + this.uuid,
      formData
    ).then((res) => {
      if (res.code == 100) {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        let fileList = this.fileList;
        fileList.push(file.name);
        this.fileList = fileList;
      } else if (res.status == 500) {
        this.$message({
          message: "上传失败,清重新上传",
          type: "warning",
        });
      }
      });
或者
  this.lianjie =
  "http://******************";
    const formData = new FormData();
   formData.append("img_file", file);
   const config = {
       headers: { "Content-Type": "multipart/form-data" },
   };
    this.axios.post(this.lianjie, formData, config).then((res) => {
    
      });

input

<input type="number" oninput="if(value.length>6)value=value.slice(0,6)" />maxlength不生效
获取粘贴的信息
@paste.native.capture.prevent="handlePaste"
   handlePaste(e) {
     var clip = e.clipboardData.getData("Text");
   }

 编辑时赋值
   this.$set(this.ruleForm, "docNum", info.docNum);
   ruleForm:是data赋值
   info.docNum:是接口返回
 ---------------
  :rules="[{ required: true, message: '请输入编号', trigger: 'blur' },]"
    prop="ruleForm.docNum"
    required
    校验
  --------------------
  

## 级联

   <el-cascader
     placeholder="请选择所属区域"
      :props="props"
      :options="options"
      v-model="item.area"
      @change="handleChange(item, index)"
    ></el-cascader>
      props: {  //data里面重新赋值
        value: "name",
        label: "name",
        children: "children",
      },
      页面添加ref
      this.$refs["getCitySelName"][0].getCheckedNodes()[0]//获取第一级选择的


## 多个话 [0]=[index]   this.$refs["getCitySelName"][index]
  -----------

datePicker(时间选择)

value-format的格式
	value-format="yyyy-MM-dd" //2018-12-27
	value-format="yyyy-MM-dd HH:mm:ss" //2018-12-27 00:00:00
	value-format="timestamp" // 1483326245000
<el-date-picker
  type="date"
   value-format="yyyy-MM-dd HH:mm:ss"
   @change="formatStartTime"
   v-model="time"
   style="width: 100%"
   :picker-options="pickerOptions"
 ></el-date-picker>
  formatStartTime(val) {
   	  this.time = val;
   },
data里面
//今日以前的时间不可选择
	 pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now() - 24 * 60 * 60 * 1000;
        },
      },
//只能选择今日以前,今日以后禁止选择
    pickerOptions: {
        disabledDate: (time) => {
          const curDate = (new Date()).getTime()
          const dateRegion = curDate 
          return time.getTime() <  8.64e7 || time.getTime() > dateRegion
        }
      },
 //禁止今天之前和14天两周之后的时间
     pickerOptions: {
        disabledDate: (time) => {
          const curDate = (new Date()).getTime()
          const day = 14 * 24 * 3600 * 1000
          const dateRegion = curDate + day
          return time.getTime() < Date.now() - 8.64e7 || time.getTime() > dateRegion
        }
      }
 //选后台返回时间段
 data里面:
      pickerOptions: {
        disabledDate: this.disabledDate,
      },
  disabledDate(time) {
      let newDataStr = this.info.dispatchTime.replace(/\.|\-/g, "/");
      let date = new Date(newDataStr);
      let timestamp = date.getTime();
      if (this.info.dealLimitTime) {    //结束时间有可能是空,所以判断下
        let newDataStr1 = this.info.dealLimitTime.replace(/\.|\-/g, "/");
        let date1 = new Date(newDataStr1);
        let timestamp1 = date1.getTime()- 24 * 60 * 60 * 1000;
        return time.getTime() < timestamp || time.getTime() > timestamp1;  
        //timestamp开始时间,timestamp1结束时间
      }
      return time.getTime() < timestamp; //8.64e7就是一天的时间戳 24*60*60*1000   两天之内 根据自己需求来定
    },    

删除二次确认提示框

  this.$confirm("你确定要删除吗?", "", {
     confirmButtonText: "确定",
     cancelButtonText: "取消",
     center: true,
   })
     .then(() => {
       this.del(id);
     })
     .catch(() => {
       this.$message({
         type: "info",
         message: "已取消删除",
       });
     });
         del(id){
         }

Select(下拉选择)

 <el-select
   multiple  //多选
    v-model="name"
    style="width: 100%"
    placeholder="请选择"
    @change="choose(index)"
    ref="team_name1"   //获取选择的label和name用
  >
    <el-option
      v-for="(item, index) in team"    //下拉选择的数据
      :key="index"
      :label="item.orgShortName"
      :value="item.orgId"
    ></el-option>

	选择时
      let name = this.$refs["team_name1"][0].options[0].currentLabel;
      let id = this.$refs["team_name1"][0].options[0].currentValue;
      let rule = this.$refs["team_name1"][0].options[0].itemSelected;  //
      let obj = { dealTeamId: id, dealTeamName: name, dealTeamType: 0 };
      if (rule) {
        this.list[index].teamList.splice(obj, 1);
      } else {
        this.list[index].teamList.push(obj);
      }
      /多个情况
        <el-select
            v-model="itn.probleCode"
           style="height: 34px; width: 100%"
            placeholder="请选择"
            ref="proam"
             >
           <el-option
              v-for="(item, inx) in problem"
              :key="inx"
              :label="item.problemType"
              :value="item.problemCode"
              @click.native="chose_pro(index,indexx,inx)"
            ></el-option>
         </el-select>
       chose_pro(index, indexx, inx) {
      if (indexx == 0) {
        let id = this.$refs["proam"][index].options[inx].currentValue;
        let name = this.$refs["proam"][index].options[inx].currentLabel;
        this.list[index].svDbjProblemtypeList[indexx].probleType = name;
        this.list[index].svDbjProblemtypeList[indexx].probleCode = id;
        this.list[index].svDbjProblemtypeList[indexx].primarySecond = 0;
      } else if (indexx >= 1) {
        let id = this.$refs["proam"][index].options[inx].currentValue;
        let name = this.$refs["proam"][index].options[inx].currentLabel;
        this.list[index].svDbjProblemtypeList[indexx].probleType = name;
        this.list[index].svDbjProblemtypeList[indexx].probleCode = id;
        this.list[index].svDbjProblemtypeList[indexx].primarySecond = 1;
      }
      console.log(this.list[index].svDbjProblemtypeList);
    },
 ## 回显
 分页功能:

轮播

竖排轮播
<el-carousel height="20px" direction="vertical" indicator-position="none" :autoplay="true">
       <el-carousel-item v-for="item in systemMsg" :key="item.id">
             <a href="javascript:void(0)" class="item">{{item.title}}</a>
         </el-carousel-item>
     </el-carousel>


单选事件

<el-checkbox  v-model="item"  @change="checked=>checkRow(checked, item)"></el-checkbox>
                       
checkRow(checked,item) {
    console.log(`checked:${checked}`)
    console.log(`item:${item}`)
  },

Radio

修改为正方形勾选

/deep/.el-radio__inner{
    border-radius: 2px;
  }

 /deep/.el-radio__input.is-checked .el-radio__inner::after {
    content: "";
    width: 8px;
    height: 5px;
    border: 1px solid white;
    border-top: transparent;
    border-right: transparent;
    text-align: center;
    display: block;
    position: absolute;
    top: 2px;
    left: 2px;
    vertical-align: middle;
    transform: rotate(-45deg);
    border-radius: 0px;
    background: none;
  }
下拉选择框,(多个时,不能重复选择)
//probleCode 相当于id,list是选择后的数组
      let list = this.list[index].svDbjProblemtypeList;
      var nary = list.sort();
      for (var i = 0; i < list.length; i++) {
        if (nary[i].probleCode == nary[i + 1].probleCode) {
          this.$message("问题信息重复,请重新选择!");
        }
      }
重复点击
import Vue from 'vue'

const preventReClick = Vue.directive('preventReClick', {
    inserted: function (el, binding) {
        el.addEventListener('click', () => {
            if (!el.disabled) {
                el.disabled = true
                setTimeout(() => {
                    el.disabled = false
                }, binding.value || 3000)
            }
        })
    }
});

export { preventReClick }
使用:在按钮上添加v-preventReClick

el-select 远程 搜索

export default {
  directives: {
    "el-select-loadmore": {
      bind(el, binding) {
        const SELECTWRAP_DOM = el.querySelector(
          ".el-select-dropdown .el-select-dropdown__wrap"
        );
        SELECTWRAP_DOM.addEventListener("scroll", function () {
          const condition =
            this.scrollHeight - this.scrollTop - 1 <= this.clientHeight;
          if (condition) {
            binding.value();
          }
        });
      },
    },
  },
}

 			<el-select
                clearable
                style="width: 100%"
                v-model.trim="checkObjId"
                placeholder="请输入选择"
                remote
                filterable
                @clear="clear()"   //清除事件
                :remote-method="remoteMethod"
                @change="checkObject"
                @focus="select_ts"
                @blur="select_ts2"
                v-el-select-loadmore="loadmore"
              >
                <el-option
                  v-for="item in object_data"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
                  <el-popover
                  placement="bottom"
                  title="无数据"
                  width="289"
                  trigger="manual"
                  content=""
                  v-model="visible"
                >
                </el-popover>
              </el-select>
	visible://显示无数据
    checkObject(e) {
      this.visible = false;
      this.remoteMethod();
    },
    //分页
   loadmore() {
      this.object_pageNO += 1;
      this.getCheckObj();
    },
    remoteMethod(e) {
      this.search_name = e || "";    //
      this.visible = false;
      this.object_pageNO = 1    
      this.getCheckObj(e);     //请求接口
    },
  getCheckObj(){
  //分页
		 if (that.object_pageNO != 1) {
          that.object_data = [...that.object_data, ...res.body.page.list];
        } else {
          that.object_data = res.body.page.list;
        }
        if (that.object_data.length == 0 && this.search_name == "") {
          this.visible = true;
        } else {
          this.visible = false;
        }
  }        
常用组件的写法
下拉选择:
 <el-form-item label="">
    <el-select
        clearable
        placeholder="请选择"
        v-model=""
      >
        <el-option
          v-for="item in []"
          :key=""
          :label=""
          :value=""
        ></el-option>
      </el-select>
   </el-form-item>
时间段选择
  <el-form-item label="检查时间:">
      <el-date-picker
         clearable
         v-model=""
         type="datetimerange"
         start-placeholder="开始日期"
         end-placeholder="结束日期"
         format="yyyy-MM-dd HH:mm:ss"
         value-format="yyyy-MM-dd HH:mm:ss"
         @change="selectCheckTime"
       ></el-date-picker>
    </el-form-item>
周选择
npm install moment  组件
<el-date-picker 
	v-model="week"
    type="week" format="yyyy 第 WW 周" 
    placeholder="选择周" 
    @change="handleWeekChange"/>
    
handleWeekChange(val){
	let date = `${new Date(val).getFullYear()}-${new Date(val).getMonth() + 1}-${new Date(val).getDate()}`;
    let firstTime = new Date(date).getTime() - 24 * 60 * 60 * 1000;
    this.startDate = `${new Date(firstTime).getFullYear()}-${new Date(firstTime).getMonth() + 1}-${new 		Date(firstTime).getDate()}`;
	console.log(this.startDate); // 开始时间
    let lastTime = new Date(date).getTime() + 5 * 24 * 60 * 60 * 1000;
    this.endDate = `${new Date(lastTime).getFullYear()}-${new Date(lastTime).getMonth() + 1}-${new Date(lastTime).getDate()}`;
	console.log(this.endDate); // 结束时间
    let year = require("moment")(val).utcOffset("+08:00").format("yyyy");
    let week = require("moment")(val).utcOffset("+08:00").format("WW");
    console.log(year, week); // 年-周
},



带搜索的分组选择
 <el-form-item label="检查分类:">
      <el-select
         clearable
         @keyup.native="$event.target.value = $event.target.value.replace(/^\s+|\s+$/gm,'')"
         filterable
         placeholder="支持模糊匹配"
         v-model.trim=""
       >
         <el-option-group
           v-for="item in jclxList"
           :key="item.checkCode"
           :label="item.checkContent"
         >
           <el-option
             v-for="cItem in item.sysCodeList"
             :key="cItem.checkItemValue"
             :label="cItem.checkItemName"
             :value="cItem.checkItemValue"
           ></el-option>
         </el-option-group>
       </el-select>
   </el-form-item>
级联选择
上传附件组件的封装
页面单个上传使用:
多个使用:
使用:
<lUpload type="upload" @success="uploadSuccess" :file-list="fileList"></lUpload>
 uploadSuccess({response, file, fileList}) {
      console.log(response, file, fileList, "success")
      
  },
<template>
  <div class="l-upload" :class="type === 'show' ? 'hidden' : ''">
    <el-upload
      :ref="refName"
      :auto-upload="autoUpload"
      :action="action"
      :headers="headers"
      :ins="ins"
      :limit="limit"
      :file-list="List"
      :on-success="(response, file, fileList) => {return onsuccess(response, file, fileList,ins)}"  //多个参数ins是多个上传附件需要的参数
      :on-error="onerror"
      :on-remove="(file, fileList) => {return onremove(file, fileList,ins)}"   //删除同理
      :on-progress="onprogress"
      :on-change="onchange"
      :on-exceed="onexceed"
      :before-upload="onbeforeupload"
      :accept="accept"
      list-type="picture-card"
    >
      <div
        style="
          width: 98px;
          height: 98px;
          display: flex;
          justify-content: center;
          align-items: center;
        "
      >
        <slot>
          <img src="./icon/add.png" style="width: 100%; height: 100%" alt />
        </slot>
      </div>
      <div class="img-slot" slot="file" slot-scope="{ file }" v-if="file.response">
        <span
          style="
            position: absolute;
            width: 100px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            bottom: 0;
            padding: 0 5px;
          "
        >{{ file.response.data.originalName }}</span>
        <img
          v-if="
            /\.(png|jpeg|jpg|PNG|JPEG|JPG)$/.test(file.response.data.fileLink)
          "
          class="el-upload-list__item-thumbnail"
          :src="getImg(file.response.data.fileLink)"
          alt
        />
        <img
          v-else-if="
            /\.(mp4|avi|wmv|mpg|mpeg|mov|rm|ram|swf|flv)$/.test(
              file.response.data.fileLink
            )
          "
          style="width: 50%; height: 50%"
          class="el-upload-list__item-thumbnail"
          src="./icon/file_type_video.png"
          alt
        />
        <img
          v-else-if="
            /\.(doc|dot|docx|DOC|DOT|DOCX)$/.test(file.response.data.fileLink)
          "
          style="width: 50%; height: 50%"
          class="el-upload-list__item-thumbnail"
          src="./icon/word.png"
          alt
        />
        <img
          v-else-if="/\.(xls|xlt|xlsx|xlsm)$/.test(file.response.data.fileLink)"
          style="width: 50%; height: 50%"
          class="el-upload-list__item-thumbnail"
          src="./icon/ex.png"
          alt
        />
        <img
          v-else-if="/\.(ppt|pot|pptx|PPT)$/.test(file.response.data.fileLink)"
          style="width: 50%; height: 50%"
          class="el-upload-list__item-thumbnail"
          src="./icon/file_type_ppt.png"
          alt
        />
        <img
          v-else-if="/\.(pdf|PDF)$/.test(file.response.data.fileLink)"
          style="width: 50%; height: 50%"
          class="el-upload-list__item-thumbnail"
          src="./icon/PDF.png"
          alt
        />
        <img
          v-else-if="
            /\.(mp3|MP3|wav|amr|m4a|awb)$/.test(file.response.data.fileLink)
          "
          style="width: 50%; height: 50%"
          class="el-upload-list__item-thumbnail"
          src="./icon/file_type_voice.png"
          alt
        />
        <img
          v-else-if="/\.(zip|rar|7z|tar)$/.test(file.response.data.fileLink)"
          style="width: 50%; height: 50%"
          class="el-upload-list__item-thumbnail"
          src="./icon/zip.png"
          alt
        />
        <img
          v-else-if="/\.(xmind|xmap|mmap)$/.test(file.response.data.fileLink)"
          style="width: 50%; height: 50%"
          class="el-upload-list__item-thumbnail"
          src="./icon/xmind.png"
          alt
        />
        <img
          v-else-if="/\.(txt)$/.test(file.response.data.fileLink)"
          style="width: 50%; height: 50%"
          class="el-upload-list__item-thumbnail"
          src="./icon/txt.png"
          alt
        />
        <img
          v-else
          style="width: 50%; height: 50%"
          class="el-upload-list__item-thumbnail"
          src="./icon/qitawenjian.png"
          alt
        />

        <span class="el-upload-list__item-actions">
          <span
            v-if="
              /\.(png|jpeg|jpg|PNG|JPEG|JPG)$/.test(
                file.response.data.fileLink
              ) ||
              /\.(mp4|avi|wmv|mpg|mpeg|mov|rm|ram|swf|flv)$/.test(
                file.response.data.fileLink
              )
            "
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span
            v-if="
              !/\.(png|jpeg|jpg|PNG|JPEG|JPG)$/.test(
                file.response.data.fileLink
              )
            "
            class="el-upload-list__item-preview"
            @click="handleD(file)"
          >
            <i class="el-icon-download"></i>
          </span>

          <span
            v-show="type !== 'show'"
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="downLoad" v-if="downLoad" :append-to-body="true">
      <div
        style="
          display: flex;
          justify-content: center;
          align-items: center;
          width: 100%;
          height: 100%;
        "
      >
        <el-carousel
          v-if="accept === 'image/*'"
          style="width: 100%; height: 100%"
          :autoplay="false"
          height="600px"
          indicator-position="outside"
          :initial-index="index"
        >
          <el-carousel-item v-for="(item, index) in List" :key="index">
            <div
              style="
                width: 100%;
                height: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
              "
            >
              <img style="height: 100%" :src="item.response.data.link" alt />
            </div>
          </el-carousel-item>
        </el-carousel>
        <video
          v-else-if="
            /\.(mp4|avi|wmv|mpg|mpeg|mov|rm|ram|swf|flv)/.test(
              files.response.data.link
            )
          "
          controls="controls"
          autoplay="autoplay"
          :src="dialogImageUrl"
        ></video>
        <img width="100%" v-else :src="dialogImageUrl" alt />
      </div>

      <!--<el-button @click="handleRemove
      ">删除</el-button>-->
    </el-dialog>
  </div>
</template>

<script>
import { getAccessToken } from "@/utils/auth";   //token
import { Notification } from "element-ui";


let _this = this;
export default {
  name: "index",
  components: {
    Notification,
  },
  props: {
    headers: {
      type: Object,
      default() {
        return {
          Authorization: getAccessToken(),
          timestamp: String(new Date().getTime()),
          sign: "",
        };
      },
    },
    type: {
      type: String,
      default: "upload", // show
    },
    refName: {
      type: String,
      default: "upload", // show
    },
    accept: {
      type: String,
      default: "",
    },
    ins: {
      type: String,
      default: "",
    },
    limit: {
      type: Number,
      default: 8,
    },
    /** 把数据列表放在父组件做统一处理,方便数据操作 **/
    action: {     //路径
      type: String,
      required: false,
      default() {
        return (
         	*******
        );
      },
    },
    autoUpload: {
      type: Boolean,
      default: true,
    },
    width: {
      type: String,
      default: "100px",
    },
    height: {
      type: String,
      default: "100px",
    },
    fileList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      disabled: false,
      files: [],
      List: [],
      ins: "",
      dialogImageUrl: "",
      downLoad: false,
      index: 0,
      imgPrefix: imgPrefix,
      timer: false,
    };
  },
  updated() {
    this.setUI();
  },
  watch: {
    fileList: {
      immediate: true,
      handler(fileList) {
        // console.log(fileList,"file")
        fileList = fileList ? fileList : [];
        if (this.fileList && this.fileList.length > 0) {
          this.List = fileList.map((item) => {
            // console.log(item)
            return {
              url: item.fileLink,
              name: item.originName,
              response: {
                data: item,
              },
            };
          });
          // console.log(this.List)
        } else {
          this.List = fileList;
        }
      },
    },
    ins(val) {
      console.log(val, "123");
    },
  },
  mounted() {
    // console.log(this.List,'12313123')
    this.setUI();
  },
  methods: {
    getImg(url) {
      return url;
    },
    setUI() {
      if (document.getElementsByClassName("el-upload--picture-card")) {
        let ele = document.getElementsByClassName("el-upload--picture-card")[0]
          .style;
        ele.setProperty("--height", this.height);
        ele.setProperty("--width", this.width);
        if (this.type === "show") {
          ele.setProperty("--display", "none");
        } else {
          ele.setProperty("--display", "inline-block");
        }
      }
      // if (document.getElementsByClassName('el-upload-list__item')) {
      //     let ele2 = document.getElementsByClassName('el-upload-list__item')[0].style
      //     ele2.setProperty("--height", this.height);
      //     ele2.setProperty("--width", this.width);
      // }
    },
    //上传成功的函数
    onsuccess(response, file, fileList, ins) {
      this.close();
      Notification({
        type: "success",
        message: "上传成功",
        title: "提示",
      });
      this.List = fileList;
      let query = {
        response: response,
        file: file,
        fileList: fileList,
        ins: ins,
      };
      this.$emit("success", query);
    },
    onerror(err, file, fileList) {
      let query = {
        err,
        file,
        fileList,
      };
      this.$emit("error", query);
      this.close();
      Notification({
        type: "error",
        message: "上传失败,请稍后重试",
        title: "提示",
      });
    },
    //删除
    onremove(file, fileList, ins) {
      Notification({
        type: "success",
        message: "移除成功",
        title: "提示",
      });
      let query = {
        file,
        fileList,
        ins,
      };
      this.$emit("remove", query);
    },
    onprogress(event, file, fileList) {
      if (!this.timer) {
        this.timer = true;
        this.open();
      }
      // console.log(event, file, fileList)
      this.$emit("progress", fileList);
    },
    onbeforeupload(file) {
    //图片压缩
    const _this = this;
      return new Promise((resolve) => {
        const reader = new FileReader();
        const image = new Image();
        image.onload = (imageEvent) => {
          const canvas = document.createElement("canvas");
          const context = canvas.getContext("2d");
          const width = image.width * 0.5;
          const height = image.height * 0.5;
          canvas.width = width;
          canvas.height = height;
          context.clearRect(0, 0, width, height);
          context.drawImage(image, 0, 0, width, height);
          const dataUrl = canvas.toDataURL(file.type);
          const blobData = _this.dataURItoBlob(dataUrl, file.type);
          resolve(blobData);
          this.$emit("beforeUpload", blobData);
        };
        reader.onload = (e) => {
          image.src = e.target.result;
        };
        
        reader.readAsDataURL(file);
      });
      //this.$emit("beforeUpload", file);
    },
     dataURItoBlob(dataURI, type) {
      var binary = atob(dataURI.split(',')[1]);
      var array = [];
      for(var i = 0; i < binary.length; i++) {
      array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {type: type});
   },
    onchange(file, fileList) {
      let query = {
        file,
        fileList,
      };
      this.$emit("change", query);
    },
    onexceed() {
      Notification({
        type: "error",
        message: "超出最大文件数量限制",
        title: "提示",
      });
    },
    /** 展示弹窗 **/
    handlePictureCardPreview(file) {
      // if (/\.(png|jpeg|jpg|PNG|JPEG|JPG)$/.test(file.response.data.fileLink)) {
      this.files = file;
      this.downLoad = true;
      // this.dialogImageUrl = this.$config.VUE_APP_IMG_PREFIX_URL + this.files.response.data.relativeLink;
      this.dialogImageUrl = this.files.response.data.fileLink;
      this.List.map((item, index) => {
        if (item.response.data.id === file.response.data.id) {
          this.index = index;
        }
      });
      // } else {
      //     this.handleD(file)
      // }
    },
    /** 移除事件 **/
    handleRemove(file) {
      this.$refs.upload.handleRemove(file);
    },
    /** 下载 **/
    handleD(file) {
      Notification({
        duration: 0,
        dangerouslyUseHTMLString: true,
        showClose: false,
        title: "提示",
        message:
          '<img style="width: 40px;height40px: " src="static/images/loading.gif"> 下载中...',
      });
      // window.open(file.response.data.fileLink, '_blank')
      const a = document.createElement("a");
      const url = file.response.data.relativeLink;
      // 这里是将url转成blob地址,
      fetch(url)
        .then((res) => res.blob())
        .then((blob) => {
          if ("download" in document.createElement("a")) {
            // 支持a标签download的浏览器// 将链接地址字符内容转变成blob地址
            a.href = URL.createObjectURL(blob);
            a.download =
              file.response.data.originName ||
              url.split("/")[url.split("/").length - 1]; // 下载文件的名字
            // a.download = url.split('/')[url.split('/').length -1] //  // 下载文件的名字
            document.body.appendChild(a);
            a.click();
            Notification.closeAll();
            Notification({
              duration: 1500,
              type: "success",
              message: "下载成功",
              title: "提示",
            });
          } else {
            navigator.msSaveBlob(blob, file.title);
            Notification.closeAll();
            Notification({
              duration: 1500,
              type: "success",
              message: "下载成功",
              title: "提示",
            });
          }
        });
    },
    //提示框开启事件
    open() {
      Notification({
        duration: 0,
        dangerouslyUseHTMLString: true,
        showClose: true,
        title: "提示",
        message:
          ' 上传中...',
      });
    },
    // 提示框关闭方法
    close() {
      Notification.closeAll();
      this.timer = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.l-upload {
  height: var(--height);
  width: var(--width);

  .img-slot {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  /deep/ .el-upload--picture-card {
    height: var(--height);
    width: var(--width);
    //display: var(--display);
  }

  /deep/ .el-upload-list__item {
    //height: var(--height) !important;
    //width: var(--width) !important;
    height: 100px;
    width: 100px;
  }

  /deep/ .el-progress-circle {
    display: flex;
    justify-content: center;
    align-items: center;
    height: auto;

    svg {
      height: 90px;
      width: 90px;
    }
  }

  /deep/ .el-upload-list__item-actions,
  .el-upload-list__item-preview,
  .el-upload-list__item-delete {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.hidden {
  /deep/ .el-upload--picture-card {
    height: 0 !important;
    width: 0 !important;
    display: none !important;
  }
}


</style>


input 类型


@blur="addAddressForm.mobilePhone = $event.target.value"  onkeyup="value=value.replace(/[^\d]/g,'')"   //数字

confirm
vue+element(项目中的使用)_第1张图片
el-row
内容一样高度

<el-row type="flex" style="flex-flow: row wrap;">
	<el-col :span="12"></el-col>
	<el-col :span="12">
		<div style="height: 100%"></div>
	</el-col>
	<div style="clear:both"></div>
</el-row>

tree

回显
	  var that = this;
      setTimeout(() => {
        that.$nextTick(() => {
          const nodes = []; 		//choseDepartment value数组
          that.choseDepartment.forEach((item) => {
            const node = that.$refs.tree.getNode(item);
            if (node.isLeaf) {
              //关键,过滤掉不是叶子节点的
              nodes.push(item);
            }
          });
          that.$refs.tree.setCheckedKeys(nodes, true);
        });
点击事件
 @check="handleCheckChange"

你可能感兴趣的:(VUE,vue.js)