Vue 日常开发问题(二)更新时间-2024-1-19

622 阅读7分钟

数据显示问题

日常开发中会遇到后台返回的数据不是前端需要的数据时候,这时候就需要用到了 filter 过滤自己需要的字符/数据

字符串截取从下标0开始到下标10 结束。 多出字符显示。。。

组件过滤器

当判断条件多时,建议使用 --switch判断语句;
 created() {
    this.valId = this.$route.meta.businessUnitPara;
      //调用--
    this.Default(this.valId)
  },
 //默认值取值
    Default(e){
        switch(e){
          case "1":
          this.form.mateHolder="SD";
          break;
          case "2":
          this.form.mateHolder="S";
          break;
          case "40":
          this.form.mateHolder="FC";
          break;
          case "41":
          this.form.mateHolder="FC";
          break;
          case "50":
          this.form.mateHolder="JG";
          break;
          case "51":
          this.form.mateHolder="JG";
          break;
        }
    },

 filters: {
    dataList(val) {
      return val.substr(0, 10) + "...";
      // console.log('vas',val)
    },
  },

数据返回为数字但需要数字对应的意思,如下 用到switch 判断

statusList(val) {
      let n = "";
      switch (val) {
        case 0:
          n = "待执行";
          break;
        case 1:
          n = "执行中";
          break;
        case 2:
          n = "执行完成";
          break;
        case 3:
          n = "执行失败";
          break;
        default:
          n = "--";
      }
      return n;
    },

全局过滤器

在api 文件夹中新建filter.js

const vFilter = {
  // 指标种类
  indexType: function (val) {
    let n = "";
    switch(val) {
      case 1: n= "原生指标"; break;
      case 2: n= "派生指标"; break;
      default: n= "--";
      // case 1: n= "调查指标"; break;
      // case 2: n= "综合指标"; break;
      // case 3: n= "分析指标"; break;
      // default: n= "--";
    }
    return n;
  },
  // 指标种类2
  indexType2: function (val) {
    let n = "";
    switch(val) {
       // case 1: n= "原生指标"; break;
      // case 2: n= "派生指标"; break;
      // default: n= "--";
      case 1: n= "调查指标"; break;
      case 2: n= "综合指标"; break;
      case 3: n= "分析指标"; break;
      default: n= "--";
    }
    return n;
  },
  // 指标种类3
  indexType3: function (val) {
    let n = "";
    switch(val) {
      case 1: n= "实物量指标"; break;
      case 2: n= "价值量指标"; break;
      default: n= "--";
    }
    return n;
  },
  // 数据表示格式
  dataType: function (val) {
    let n = "";
    switch(val) {
      case 1: n= "文本"; break;
      case 2: n= "数值"; break;
      case 3: n= "日期"; break;
      case 4: n= "代码"; break;
      case 5: n= "字母"; break;
      case 6: n= "整数"; break;
      case 7: n= "其他"; break;
      default: n= "--";
    }
    return n;
  },
  // 状态1
  state1: function (val) {
    let n = "";
    switch(val) {
      case 1: n= "未发布"; break;
      case 2: n= "已发布"; break;
      case 3: n= "已认领"; break;
      case 4: n= "未认领"; break;
      default: n= "--";
    }
    return n;
  },
  // 状态2
  state2: function (val) {
    let n = "";
    switch(val) {
      case 0: n= "创建中"; break;
      case 1: n= "已完成"; break;
      default: n= "--";
    }
    return n;
  },
  // 状态3
  state3: function (val) {
    let n = "";
    switch(val) {
      case 0: n= "停用"; break;
      case 1: n= "启用"; break;
      default: n= "--";
    }
    return n;
  },
  // 指标状态
  status: function (val) {
    let n = "";
    switch(val) {
      case "0": n= "停用"; break;
      case "1": n= "启用"; break;
      default: n= "--";
    }
    return n;
  },
  
  // 指标分组标识
  indexGroupTag: function (val) {
    let n = "";
    switch(val) {
      case 1: n= "指标"; break;
      case 2: n= "分组"; break;
      case 3: n= "目录"; break;
      default: n= "--";
    }
    return n;
  }
}
export default vFilter

在main.js 引入后全局使用

import vueFilter from './api/filter'
for (let key in vueFilter) {
  Vue.filter(key, vueFilter[key])
}

使用直接在组件使用就行 例如: | indexType3 为全局定义的过滤方法

 <li>
      <span>分组种类3:</span>{{ dirCodeTableData.indexType | indexType3 }}
  </li>

其他用法可自行百度。

记录一下css 样式 文字左边竖线

h4 {
    position:relative;
    color: #409EFF;
    font-size:20px;
    padding-left:16px;
    margin-right:20px;
    margin-bottom:20px;
    &:before{
      position:absolute;
      left:0;
      top:2px;
      content:"";
      width:5px;
      height:24px;
      background:#409EFF;
    }
  }
 // <span class="xian"></span>使用状态统计</span>
  .xian {
  position: relative;
  display: inline-block;
  top: 2px;
  margin-right: 8px;
  width: 3px;
  height: 17px;
  background: #579af0;
}

# 使用vue获取数据时,共有N条数据,只需要前3条,怎么处理

微信截图_20210728161603.png

index 需要多少就写多少

vue获取上一个页面路由 this 不起作用

 beforeRouteEnter(to, from, next) {
   next(vm=>{          //  这里的vm指的就是vue实例,可以用来当做this使用
      console.log(to)
      console.log(from)
    })
  }

获取dom 文档高度

/生命周期/

  window.addEventListener('resize', this.getHeightss);
    this.getHeightss()
    /方法/
getHeightss(){
          this.heightList=window.innerHeight-210+'px';
       },

给div添加滚动条

<div style="height:300px;width:100px;overflow:auto"><div/>(height和width根据需求设定)

注意:如果只写height就只有垂直滚动条,只写width就只有水平滚动条,都不写没有效果。还有这里overflow设置为auto,也就说是如果** **你的页面高度大于300px就会出现滚动条,小于300px就没有滚动条。同理,如果宽度大于100px出现滚动条,小于就没有。**

 

你也可以将overflow设置为scroll,即: <div style="height:300px;width:100px;overflow:scroll"><div/>。这样设定的效果为****

不管你的页面高度大于还是小于300px,都会出现滚动条,宽度同理。

 

也可以这样设置:

水平滚动条: <div style="width:100px;overflow-x:auto"></div>

垂直滚动条: <div style="height:300px;overflow-y:auto"></div>

水平加垂直: <div style="width:100px;height:300px;overflow-x:auto;overflow-y:auto"></div>

Input 添加纯数字校验去调e 给input添加oninput

<el-input v-model="form.desc"  oninput="value=value.replace(/[^\d]/g,'')" class="Input" />

全局弹框实现局部刷新的效果,(要求--里面有个刷新按钮--)

---在table 组件上添加 v-loading="loadings" 点击按钮后为true,多少毫秒后为false 可以局部刷新

 //刷新
    refreshBtn(){
      this.loadings = true;
      setTimeout(()=>{
        this.loadings =false
      },500)
      this.$refs.multipleTable.clearSelection();
    },

全面清除table 选择按钮/多选框

---在table 组件上添加ref="multipleTable"

  <el-table  ref="multipleTable" 
  :max-height="maxHeight" :height="maxHeight" 
  :data="gridData" border style="width: 100%" v-loading="loadings"
              @selection-change="handleSelection"
              >
this.$refs.multipleTable.clearSelection();

数据修改成后端需要的字段---JSON数据,改为{},

 其他方式没试,哈哈,大佬有什么简单的方法可以借鉴一下子!!!!
原始数据格式 //[{…} __ob__: Observer]
修改后的数据格式 {…}
let obj={}
        this.returnDataDialog.map((item=>{
          obj=item
        }))

把数据插入现有的数据替换原来的数据

this.$set() 进行替换
 this.returnDataDialog.map(item=>{
          this.$set(item,"tzCode",this.formId)
        })
  //form表单 this.$set(this.formSpecial,"exchangeqty",response.data.qty*response.data.cnvRate)

2022-12-16T10:24:00.000+08:00 改成 2022-12-16 最简单方法 (写入插值表达式)

废弃---
<el-table-column prop="endTime" label="处理时间" align="center" >
     <template slot-scope="scope">
          <span>{{new Date(scope.row.endTime).toLocaleDateString()}}</span>
     </template>
 </el-table-column>
 
 1,用浏览器提供的 `toLocaleString` 接口来实现。同样输出 `2019-09-27 16:23:21` 这样的格式。
 new Date().toLocaleString('zh', { hour12: false }).replaceAll('/', '-')
 2,如果只想获取日期也可以用 `toLocaleDateString` 接口,例如输出 `2019-09-27` 这样的格式
 new Date().toLocaleDateString('zh').replaceAll('/', '-');
 3,如果只想获取时间也可以用 `toLocaleTimeString` 接口,例如输出 `16:23:21` 这样的格式
 new Date().toLocaleTimeString('zh', { hour12: false })

第二种方法

 在momethods里面写
filterTime(time) {
        var date = new Date(time);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        var d = date.getDate();
        d = d < 10 ? "0" + d : d;
        var h = date.getHours();
        h = h < 10 ? "0" + h : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? "0" + minute : minute;
        var s = date.getSeconds();
        s = s < 10 ? "0" + s : s;
        return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + s;
      },
      //调用
    this.filterTime(data)

##第三种

getCurrentTime() {
        //获取当前时间并打印
        var _this = this;
        let yy = new Date().getFullYear();
        let mm = new Date().getMonth()+1;
        let dd = new Date().getDate();
        let hh = new Date().getHours();
        let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
        let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
        return  _this.gettime = yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
    }
    
    调用  this.getCurrentTime()

监听form表单数据 后计算

微信截图_20230116153419.png 缺点总价的input 不能修改,只能修改单价和数量-----有大佬知道什么问题么-请教

🤣😂


api 接口 get 请求方式问题

例如 url?pageNum=1&pageSize=10&isflow2=1

 用此方法 
    export function was(query) {
  return request({
    url: '/wa/a/b',
    method: 'get',
    params: query
  })
}

例如 url/ec768ecc392c4ed5b61a8829c8eeeae0

export function was(id) {
  return request({
    url: '/wa/a/b/' + id,
    method: 'get'
  })
}

例如 /url?id=135d62fba14149c5b9c730907aa843b5

export function was(id) {
  return request({
    url: '/wa/a/b?id='+id,
    method: 'get',
  })
}
**------------**
POST 
export function was(data) {
  return request({
    url: '/wa/a/b',
    method: 'post',
   data
  })
}
export function checkExist(params) {
  return request({
    url: '/ems/emsSupp/CheckSuppCode?suppCode='+params,
    method: 'post',
  })
}

export function meterialList(params) {
  return request({
    url: '/ems/emsStadMate/repeatCode',
    method: 'post',
    params
  })
}

element日期选择器限制

可查看链接----    https://www.cnblogs.com/Ao-min/p/17027747.html

传入后端需要的字段 例如:

{
  "ids": [
    {
      "id": "132",
      "status": "0"
    },
    {
      "id": "132",
      "status": "0"
    }
  ]
}

写法如下

    let arr=[]
         this.idsList.forEach((item=>{
            arr.push({
              id:item.id,
              status:item.status
            })
         }))
         // 声明一个对象赋值 为 ids的数组 赋值arr     ----->  {ids:[{},{}] }
         let obj={ids :[...arr]}
         

element ui tabel 表格行内编辑

     oninput="value=value.replace(/\D/g,'')"  ///正则只能输入正整数
1------ 在tabel 添加属性 如下
    <el-table  @cell-dblclick="dbclick" :cell-class-name="tableCellClassName"></el-tabel>
2------在表格某一行设置 显示input /span
    <el-table-column prop="doqty" label="本次发放量" width="120">
                <template slot-scope="scope">
                      <el-input
                        @blur="hideInput"
                        size="mini"
                        :ref="scope.row.index + ',' + scope.column.index"
                        v-model="scope.row.doqty"
                       oninput="value=value.replace(/\D/g,'')"
                        v-if="
                          scope.row.index + ',' + scope.column.index ==
                          currentCell
                        "
                        clearable
                      >
                      </el-input>
                      <span v-else>{{ scope.row.doqty }}</span>
                    </template>
              </el-table-column>
  3------在方法里面写逻辑
       // 给单元格绑定横向和竖向的index,这样就能确定是哪一个单元格
      tableCellClassName({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex;
      column.index = columnIndex;
    },
    //双击事件
    dbclick(row, column) {
      // 用 switch判断不然focus() 报错
      switch (column.label) {
          ////// 本次发放量   对应表格本次发放量 的一行
        case "本次发放量":
          this.currentCell = row.index + "," + column.index;
          setTimeout(() => {
            // 双击后自动获得焦点
            this.$refs[row.index + "," + column.index].focus();
          });
          break;
      }
    },
    // 当input失去焦点的时候,隐藏input
    hideInput(e) {
      // console.log("🚀 ~ file: appliCation.vue:928 ~ hideInput ~ e:", e)
      this.currentCell = null;
    },

element-ui 避免一个页面弹出多个Message

// 单独引入 message  
import {Message} from 'element-ui'
 // 在需用的--方法里面调用 
 循环里面调用 ---
      Message.closeAll()    // 调用
              this.$message({
              message: '不能为空',
              type: 'warning'
            });

form 表单验证身份证是否合法

    //在return 外面写验证规则
    // 身份证验证
    var validatorIdCard = (rule, value, callback) => {
    // 地区
      var aCity={ 11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",
        21:"辽宁",22:"吉林",23:"黑龙江",
        31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",
        41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",
        51:"四川",52:"贵州",53:"云南",54:"西藏",
        61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",
        71:"台湾",81:"香港",82:"澳门",91:"国外"};
        // 验证长度
      if(!/^\d{17}(\d|x)$/i.test(value)){
        callback(new Error('您输入的身份证号长度或格式错误,请输入正确的身份证号'));
        return;
      }
      // 验证前两位是否为省份代码
      value=value.replace(/x$/i,"a");
      if(aCity[parseInt(value.substr(0,2))]==null){
        callback(new Error('您输入的身份证号长度或格式错误,请输入正确的身份证号'));
        return;
      }
      // 身份证上的出生年月校验
      var sBirthday=value.substr(6,4)+"-"+Number(value.substr(10,2))+"-"+Number(value.substr(12,2));
      var d=new Date(sBirthday.replace(/-/g,"/")) ;
      if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate())){
        callback(new Error('您输入的身份证号不合法,请输入正确的身份证号'));
        return;
      }
      // 身份证校验位判断
      var iSum=0 ;
      for(var i=17;i>=0;i--) {
        iSum += (Math.pow(2,i) % 11) * parseInt(value.charAt(17 - i),11) ;
      }
      if(iSum%11!=1){
        callback(new Error('您输入的身份证号不合法,请输入正确的身份证号'));
        return;
      }
      callback()
    };
    //在form 表单验证引入
    //表单验证
        //validator: validatorIdCard 自定义验证 
        // 表单非必填验证  required: false,
      rules: {
         idcardnumber: [
           { required: true, validator: validatorIdCard, trigger: 'change' },
         ],
      },

获取table 的label和value

1.在 tabel 上面绑定ref
    <el-table ref="multipleTable"></el-tabel>
2.在方法里面设置:
    aaa() {
      let arr = []
      this.$nextTick(() => {
        this.$refs.multipleTable.$children.forEach((obj) => {
          arr.push({
            label: obj.label,
            prop: obj.prop
          });
          console.log('[ arr ] >', arr)
        });
      })

    },
    调用this.aaa()

微信截图_20230307103908.png

el-input文本框v-model数据改变时不刷新的问题 、可以在赋值的结尾加上this.$forceUpdate()强制更新

aa(){
    this.form.vmiInvoiceInputer = this.$store.state.user.name;
        this.form.vmiInvoiceDate = new Date();
        this.$forceUpdate()  //强制刷新
}
        

package.json文件中常见的版本号及限定符

下面分别说明限定符号的含义:

^0.1.0:支持0.1.0 ~ 1.0.0之内的所有版本。
~0.1.0:支持0.1.0 ~ 0.2.0之内的所有版本。
0.1.0:锁定0.1.0版本。
>=0.1.0:支持大于等于0.1.0之后的所有版本。
*:任意版本。
由此可见:^表示大版本的升级,~表示小版本的升级。

el-tabel 树结构按需加载问题

<el-table
              
              v-loading="treeLoading"
              :data="mateCodeList"
              row-key="nodeId"
              :default-expand-all="isExpandAll"
              highlight-current-row
              @row-click="handleRowClick"
              :height="maxHeightDop"
              :max-height="maxHeightDop"
              :load="load" //官网文档添加
              lazy   //官网文档添加
              :tree-props="defaultProps" //官网文档添加
            >
              <el-table-column
                v-for="(item, index) in treeColumns"
                :prop="item.prop"
                :label="item.label"
                :show-overflow-tooltip="true"
                :key="index"
              ></el-table-column>
            </el-table>
   data(){
       return{
           //添加tree 结构树
            defaultProps:{
                children: [],
                label: "treeTitle",
                hasChildren: "has",
              },
              // 表头数据
            treeColumns: [
                {
                  prop: "treeTitle",
                  label: "21",
                },
                {
                  prop: "text1",
                  label: "3",
                },
                {
                  prop: "text2",
                  label: "5",
                },
      ],
   
   },
   methods:{
       //默认传0 ----根据实际后端要求来定---
       getTreeselect(id = 0) {
      this.treeLoading = true;
      //1 接口数据
      treeselect({ typeId: 0 },this.routeFlag).then((res) => {
        if (res.code == 200) {
          this.mateCodeList = res.data.map((item) => {
            item.has = item.has == 1 ? false : true;   
            // has-后端数据显示的小箭头。 后台数据需要和tree 数据相同
            return item;
          });
          this.treeLoading = false;
          // this.treeId = response.data[0]?.nodeId;
          // this.queryParams.mateCode = response.data[0]?.treeTitle;
          // this.handlegetList(this.treeId);
        } else {
          this.$message.error("获取数据失败!");
        }
      });
    },
   
       //tree表格懒加载
    load(tree, treeNode, resolve) {
           //2 接口须和上面接口一致  (1=2)
      treeselect({ typeId: tree.nodeId }).then((res) => {
        res.data.map((item) => {
          item.has = item.has == 1 ? false : true;
          return item;
        });
        resolve(res.data);
      });
      
    },
   }

记录el-table 选中或者取消某一个时赋值问题

微信截图_20230515183533.png

如图 选中后赋值问题,见代码:

 // 1.选中取消选中赋值
     -------全部数据
      this.options.tableData.forEach(it=>{
        this.$set(it,'wqty',0)
      })
      ------选中的数据
      this.processTopSelection.forEach(item=>{
        this.$set(item,'wqty',item.issueqty)
      })
  // 2.
   const returnData = JSON.parse(
    JSON.stringify(this.$refs.lnlineEditing.returnData)   // 组件绑定ref 获取整条数据
  );

  this.options.tableData.forEach((item) => {
    this.$set(item, "wqty", 0);
  });
  // console.log(this.$refs.lnlineEditing.returnData, "retun");
  if (returnData.length) {
    selection.forEach((item) => {
      let o = returnData.find((i) => {
        if (i.id == item.id && i.wqty) {
          return item;
        }
        if (o) {
          this.$set(item, "wqty", o.wqty);
        } else {
          this.$set(item, "wqty", item.issueqty);
        }
      });
    });
  } else {
    selection.forEach((item) => {
      this.$set(item, "wqty", item.issueqty);
    });
  }
  selection.forEach((item) => {
    if (returnData.length) {
      returnData.forEach((i) => {
        if (item.id == i.id) {
          console.log(i.wqty, "&&9");
          if (i.wqty) {
            this.$set(item, "wqty", i.wqty);
          } else {
            this.$set(item, "wqty", item.issueqty);
          }
        }
      });
    } else {
      this.$set(item, "wqty", item.issueqty);
    }
  });

动态修改el-table 表头样式

 <el-table
:header-cell-style="headCellStyle"
 </el-table>
 
 props: {
    headCellStyle:{
      type:Function,
      default:function(){}
    }
  },
  
  子组件--
   :headCellStyle="headCellStyle"
   
   方法:
   headCellStyle({row, column, rowIndex, columnIndex}){
     if(columnIndex==4){
      return {background:'rgb(204, 204, 204) !important'}
     }
    }

keepAlive 缓存问题

遇到问题:在首页跳转指定的页面,传id 会渲染指定的数据,然后在菜单中再次进入这个页面后出现缓存,但这时不需要缓存,

解决代码 在生命周期里面如图:

1.
created() {
    if(this.$route.meta.keepAlive==true){
      this.$destroy(); //组件摧毁
    }
  },
  2.
  // 钩子函数   在页面创建前就执行的
  //to:里面是当前页面的路由对象。
  //from:里面是上一个页面的路由对象。
  //next:表示进入当前页面,beforeRouteEnter 内必须执行 next() 
  beforeRouteEnter(to, from, next){
      to.meta.keepAlive=false
      next()
    },
  //在页面离开后执行
  // beforeRouteLeave(to, from, next){
  //     this.$route.meta.keepAlive==false
  //     next()
  //   }
  
  

遇到只需要某个对象里面的值,后再从新铸件新的数据

例如1:
    原数据 :
    [        {         id:1,         name:zhan     },     {         id:2,         name:zhan2     }    ]
   需要类型 :  [{1:zhan},{2:zhan2}]
    let arr=[];
        this.tableData.forEach(item=>{
          arr.push({[item.id]:item.name})
        })
        
        /// 打印  [ { '1': 'zzzz' }, { '2': 'zzz222z' } ]

字符串处理-rgb(255,255,255)-处理为 255,255,255

如图所示

image.png

判断数据状态是否能操作是可用:

check(){
      return (this.statusData=="0" || this.statusData=="10")
    },
    //调用时  this.check()  如果有里面的值返回true 否则false

image.png

字符穿带有下划线的转驼峰

  // 把json配置需要的字段后先把大写的值转化为小写后再转成驼峰
this.listTableColumsBoms= this.listTableColumsBom.map(item=>{
       return{
          prop: this.nameToHump(item.fieldName.toLowerCase()),
          label: item.fieldAlias,
        }
      })
      
    // 驼峰方法
    nameToHump(name) {
    return name.replace(/\_(\w)/g, function (all, letter) {
        return letter.toUpperCase();
    });
},

持续更新中----