Vue基本语法

1.遍历循环及过滤filter:可参考:https://www.cnblogs.com/liuzhengkun/p/11216966.html


  • 筛选和排序1

  • 筛选和排序2

  • 对象数组分组,排序

 // 作业指导书分组筛选
    f_HandleTableList(data)
    {
      // 1.先排序
      data = data.sort(this.f_ArraySort("version","Desc"));//按照版本降序排列
      // 2.后按照工序号分组,取每组中版本最大的记录
      const newData =this.f_GroupBy(data, function (item) {
            return [item.fileName];//按照name进行分组
        });
      const newArr =[];
       
      // 这种方式是获取了每组中version最大的version值
      // newData.forEach(e => {
      //   var result = Math.max(...e.map(x => x.version));
      //   if(result)
      //   {
      //     newArr.push(result);
      //   }
      // });

      newData.forEach(e => {        
        newArr.push(e[0]);//取每组中的第一项       
      });
      this.mainTableList = newArr;
      this.mainTotal = newArr.length;
      console.log(newData.length);
    },
    // 排序
    f_ArraySort(property,type) {
        return (firstobj, secondobj) => {
            const firstValue = firstobj[property];
            const secondValue = secondobj[property];
            switch (type) {
                case "Desc":
                    return secondValue - firstValue; //降序
                case "Asc":
                    return firstValue - secondValue; //升序
                default:
                    return firstValue - secondValue; //升序
            }
        };
    },
    // 分组
    f_GroupBy: function(array, f) {
     let groups = {};
     array.forEach(function(o) {
       let group = JSON.stringify(f(o));
       groups[group] = groups[group] || [];
       groups[group].push(o);
     });
     return Object.keys(groups).map(function(group) {
       return groups[group];
     });
   },
    // 获取产线
    f_QueryArea() {
      const queryParams = {
        sorts: [
          {
            columnName: 'CreateDt',
            direction: 2
          }
        ],
        conditions: []
      };
      api_getareadata(queryParams).then((response) => {
        if (response.success === true) {
          this.areadata = response.data;
        }
      });
    },
2.VUE-Element组件-select选择器的使用 参考:https://blog.csdn.net/gu_wen_jie/article/details/84281915

下拉框:


默认选中:详解element-ui中el-select的默认选择项问题 https://www.jb51.net/article/166813.htm

3.VUE-Element组件-checkbox复选框的使用

         <el-col :span="8">
              <el-form-item label="线路板适配厂商" prop="manufacturer">
                <el-checkbox-group v-model="requirementData.manufacturer" :disabled="editData.type==1||isExamine">
                  <el-checkbox label="BJ" />
                  <el-checkbox label="BBT" />
                  <el-checkbox label="运营商" />
                </el-checkbox-group>
              </el-form-item>
            </el-col>

初始化data时:

 requirementData: {
     manufacturer: '', // 厂商
},
checkList: []  // 订单要求多选线路板适配厂商

这里manufacture在初始化时默认赋值是字符串,这样的话,上面的复选框点击其中任一个都是全选,
应该改成:

  mounted() {
    this.f_InitialData(); // 初始化数据源
  },
 methods: {
  // 初始数据值
    f_InitialData: function() {
        this.requirementData.manufacturer = this.checkList;// 线路板适配厂商(特别注意:这里一定要赋空的数组,必须是数组,如果不赋数组则效果就是点击任一个checkbox都是全选)
    }
}  

新增存盘时参数值:

       var info = this.requirementData; // 生产任务要求
      let stringData = '';
      if (info.manufacturer.length > 0 && info.manufacturer !== null) {
        info.manufacturer.forEach((item) => {
          stringData += item + ',';//把线路板厂商字段存的数组转化为字符串方便保存到数据库中
        });
      }

保存后数据库中的字段存的是字符串:

编辑时获取厂商数据:

  const info = response.data[0];
            this.checkList = [];//定义数组接收获取的厂商
            info.manufacturer.split(',').forEach((item) => {
              if (item !== '') {
                this.checkList.push(
                  item
                );//因为保存到数据库中的是字符串,页面中要显示checkbox还需将字符串转化为数组赋给页面中的字段
              }
            });
            this.requirementData.manufacturer = this.checkList;// 线路板适配厂商(再把数组赋给requirementData.manufacturer,这样编辑就可获取到厂商数据checkbox)
  • element ui checkbox实现单选效果

4.foreach终止循环:


这样的效果 return 无效 代码继续向下执行输出了11

解决办法1:用for循环即可

解决方法2:通过抛出异常的方式实现终止。

 try {
       this.bomGoupData.forEach(element1 => {
       if (element1['bomType'] === '1') {
          existStandardBom = true;
          throw new Error('待变更的BOM列表有标准BOM 不允许变');// 这里抛出异常是为终止foreach循环
       }
      });
    } catch (error) {
      // throw new Error('待变更的BOM列表有标准BOM 不允许变更');
   }


解决方法3. for...of 是es6推出的迭代器,号称最简洁,可以是用 break,continue和 return 终止循环。跟 .forEach() 不同的是,不提供数组索引。跟 for 语句相比代码少得多,更简洁。

  // 下面代码遍历输出数组,如下:
  for(const item of articles){
    console.log(item);
  }

补充:JavaScript跳出循环的三种方法(break, return, continue) https://www.jb51.net/article/166574.htm

5. checkbox禁用:


6.vue基于element-ui select下拉框获取value和label的值 (参考链接:https://blog.csdn.net/weixin_43776272/article/details/103595596 https://blog.csdn.net/M_SSY/article/details/82882474)








6.1 vue基于element-ui select下拉框动态绑定数据



    // 增加物料明细
    f_AddBomDetail(item){
      let arrUnitData = [];
      this.unitData.forEach(element => {
        this.assistUnitData.forEach(o=>{
          if (element.unitName === o.assistUnit ) {
            arrUnitData.push(element);
          }
        });       
      });
      // 判断辅计量单位是否有数据,没数据则只赋一个当前物料的主单位(保证:该物料有辅助计量单位则可选辅助计量单位,没有则只显示主单位,不可选择其他单位)
      if(arrUnitData.length<=0){
        arrUnitData.push({ 'id': item.id, 'unitName': item.unit, 'disabled': true });
      }
      // 添加该行                    
      this.bomGoupDetailData.push({ materialNo: item.materialNo, materialName: item.materialName,
      selectionType: item.selectionType, bomSelectionId: item.pmBomSelectionId, bomSelectionName: item.pmBomSelectionName,
      importantattrs: item.importantattrs, remark: item.remark, displayNo: 1,
      number: 1, numberMo: 1, numberType: 1, unit: item.unit,
      pmAreaId: '', pmAreaName: '', pmProductProcessId: '', pmProductProcessName: '', pmProductProcessCd: '', unitData:arrUnitData });
      for (var i = 0; i < this.bomGoupDetailData.length; i++) {
            this.bomGoupDetailData[i].displayNo = i + 1;
          }
    },

7. vue filter( ) 过滤数组方法 参考:https://www.pianshen.com/article/719010572/
 
<div id="div">  
<li v-for="n in evenNumbers">{{ n }}</li>
</div>
 
<script>
varvm=new Vue({
el:"#div",
data:{
  numbers: [ 1, 2, 3, 4, 5 ]
},
computed:{
  evenNumbers: function () {
    return this.numbers.filter(function (number) 
	{
      return number<4
    })
  }
}
})
 
</script>

在计算属性不适用的情况下 (例如,在嵌套 v-for 循环中(多重v-for 嵌套)) 你可以使用一个 method 方法:

8.Vue对Element中的el-tag添加@click事件无效 (借鉴:https://blog.csdn.net/qq_17831715/article/details/104955214)
  • 1.设置无效
<el-tag type="error" @click="onClick(scope.row.blog)">scope.row.blog.title}}</el-tag>
  • 2.设置有效
<el-tag type="error" @click.native="onClick(scope.row.blog)">scope.row.blog.title}}</el-tag>
  • 3.原因:
9.非空判断:参考:https://www.oschina.net/question/3258273_2312993?sort=time
  • 1
  • 2
  • 3 使用闭包
undefined == this || !this.key ||(()=>{/*在这里执行key有值的操作*/})();
  • 4 js判断null和undefined直接就是 if(!this.key),还得判断空字符串那就只能 if(!this.key && this.key!='')
9. Vue数组去重两种方法:
  • 1.用2个for循环,判断每一项的id,
// that.positions.map(train=>{
//     that.new_Positions.push( train.trainId)
// })
//     that.resultArr = [];//去重后的数组
//     var flag;
//     for (var i in that.new_Positions){
//         flag = true;
//         for (var j in that.resultArr) {
//             if (that.resultArr[j] == that.new_Positions[i]) {
//                 flag = false;
//                 break;
//             }
//         }
//         if (flag) {
//             that.resultArr.push(that.new_Positions[i]);
//         }
//     }
// console.log("that.resultArr:",that.resultArr)
  • 2.用... new set 实现(注:数组不能是对象数组,只能是形如:[1,3,4,5,6,6,7,6,8] 这种数组)
that.positions.map(train=>{
    that.new_Positions.push(train.trainId)
})

that.new_Positions = [...new Set(that.new_Positions)];
console.log("that.resultArr:",that.new_Positions)
  • 3.对象数组去重:
    一般的数组去重可以用 ...new Set() 方法即可,但是数组对象的话,比较复杂,不能直接用,可以采取间接的方法来去重
unique(arr) {
  const res = new Map();
  return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1))
}

 <el-button type="primary" size="medium" @click="quChong()">去重</el-button>
quChong() {
        let arr = [
          {
            id: 1,
            name: '111'
          },
          {
            id: 1,
            name: '111'
          },
          {
            id: 2,
            name: '222'
          },
          {
            id: 3,
            name: '333'
          }
        ];
        console.log(arr);
        console.log('--------------------');
        let arr1 = this.unique(arr);
        console.log(arr1);
      },
      unique(arr) {
        const res = new Map();
        return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
      },

10.表单中的文本框并列显示

解决方法:设置el-form的 inline 属性可以让表单域变为行内的表单域。

参考:https://blog.csdn.net/fqxzzy/article/details/107637921

11.Element ui-input文本框自定义模板:


     <el-row>
      <el-form-item label="技术文件名" prop="noticeCode">
        <!-- <el-input v-model="editData.noticeCode" placeholder="请输入技术编码" maxlength="25" /> -->
        <el-autocomplete
          v-model="editData.noticeCode"
          class="inline-input"
          popper-class="my-autocomplete"
          :fetch-suggestions="querySearch"
          placeholder="请输入技术文件名"
          clearable
          @select="handleSelect"
          @change="changeSelect"
        >
          <i slot="suffix" class="el-icon-edit el-input__icon" @click="handleIconClick" />
          <template slot-scope="{ item }">
            <div class="name">{{ item.noticeCode }}</div>
          </template>
        </el-autocomplete>
      </el-form-item>
    </el-row>

querySearch(queryString, cb) {
      debugger;
      var noticeCodeDatas = this.noticeCodeDatas;
      var results = queryString ? noticeCodeDatas.filter(this.createFilter(queryString)) : noticeCodeDatas;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (noticeCodeDatas) => {
        return (noticeCodeDatas.noticeCode.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      console.log(item);
      this.editData.noticeCode = item.noticeCode;
      this.f_QueryVersionData(item);
    },
    handleIconClick(ev) {
      console.log(ev);
    },


12.Element-UI 上传组件缩略图删除方法(参考地址:https://blog.csdn.net/shadow_yi_0416/article/details/113545684)
     <el-row>
            <el-form-item label="图片上传">
              <el-upload
                ref="pictureUpload"
                :on-success="f_handleImageSuccess"
                :before-upload="f_HandleImageBefore"
                :on-remove="handleRemove"
                :action="imageurl"
                list-type="picture-card"
                :auto-upload="true">
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{file}">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url" alt=""
                    >
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleDownload(file)"
                      >
                        <i class="el-icon-download"></i>
                      </span>
                      <span
                        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="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-row>


 //************附件上传 */
    // 文件格式及文件大小验证
    f_HandleImageBefore(file) {
      this.tempFileName = file.name ? file.name : '临时文件名';// 文件名
      let isJPG = false;
      if (file.name.indexOf('.pdf') > -1 || file.name.indexOf('.doc') > -1 || file.name.indexOf('.docx') > -1 || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png') { isJPG = true; }
      let isLt2M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error('上传文件只能是pdf/doc/docx/jpg/jpeg/png格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!');
      }
      return isJPG && isLt2M;
    },
    // 文件上传成功
    f_handleImageSuccess(file) {
      if (file.success) {
        this.$message({ showClose: true, message: '上传成功!', type: 'success' });
        let name = file.data[0].filE_NAME;
        let url = file.data[0].path;
        // this.fileList.push({ name: name, url: url });
        this.tempFileName = '';// 每次上传完文件都将临时文件名置空
        this.uploadloading = false;
      } else {
        this.$message({ showClose: true, message: file.message, type: 'error' });
        // this.uploadloading = false;
      }
    },
    // ***********图片上传
    // 图片删除
    handleRemove(file) {
      //this.$refs.pictureUpload.handleRemove(file);// 这种也可以删除但是会报错
      const index = this.$refs.pictureUpload.uploadFiles.findIndex(text => text.url === file.url);
      this.$refs.pictureUpload.uploadFiles.splice(index, 1);//删除
      // this.$refs.pictureUpload.uploadFiles = [];// 清空
      // this.infoFrom.out_img = '';
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 图片下载
    handleDownload(file) {
      // window.open(file.response.data[0].path);
    },


13.element-ui:el-popconfirm弹出框组件确认按钮触发方法绑定



  <el-table-column label="客户代码" width="230px" header-align="center" align="center" :show-overflow-tooltip="true">
     <template slot-scope="scope">
      <span v-if="scope.row.edit3">
        <span style="width:180px;display:inline-block;">
          <el-input v-model="newCode" />
        </span>

        <el-popconfirm title="确认编辑?" 
            @onConfirm="f_Confirmss()" 
            @onCancel="f_Cancelss()">
          <el-link slot="reference" type="primary" style="margin-left:14px;" @click="f_Savess(scope.$index,scope.row)"> <i class="el-icon-check" /></el-link>
        </el-popconfirm>
      </span>

      <span>{{ scope.row.MATERIAL_NO !=null? scope.row.CUSTOMER_CODE:scope.row.CUSTOMER_CODE }}
        <el-link type="primary" @click="f_Editss(scope.$index,scope.row)"> <i class="el-icon-edit" style="margin-left:14px;" /></el-link>
      </span>
    </template>
  </el-table-column>



    // 点击取消
    f_Cancelss() {
      this.f_QueryList();
    },
       // 点击保存
    f_Savess(index, row) {
      this.currentIndex = index;
      this.currentRowData = row;
    },
     // 点击确认
    f_Confirmss() {
      const param = {
        newCode: this.newCode,
        id: this.currentRowData.ID,
        sid: this.currentRowData.SUPPLIER_ID,
      };
      api_customerCodeupdate(param).then(response => {
        if (response.success === true) {
          this.$message({
            showClose: true,
            message: response.message,
            type: 'success'
          });
          this.f_QueryList();
        } 
        this.mainTableLoading = false;
      });
    },
    // 点击编辑
    f_Editss(index, row) {
      this.mainTableList.forEach((item, index) => {
        this.mainTableList[index].edit3 = false;
      });
      this.newCode = row.CUSTOMER_CODE;
      this.mainTableList[index].edit3 = true;
    },
14.Element ui Table表格匹配字典项中的数据
  • 需求:table表格中有一列:类型,不同的类型编号对应不同的文本描述,如果少的话则可以如下写法:

    如果类型编号较多,不能直接写死文本描述,可以如下:

15.图片展示:



16.获取引用组件的数据:

17.JSON.parse(JSON.stringify(this.detailData)) 用法 (注:detailData ={} 是一个对象,不是[] 数组)

posted @ 2021-06-21 09:29  朕在coding  阅读(378)  评论(0编辑  收藏  举报