前端小知识

目录

1,下载模板文件,后端接口返回工作流,前端处理后才可以下载

2,input框验证及使用方法

3,数组对象根据某个key值去重

4,input 框阻止默认回车换行

5,数据上移下移

6,a标签下载文件,并自定义文件名

7,随机生成具有唯一性的字符串方法

8,转化时间戳


1,下载模板文件,后端接口返回工作流,前端处理后才可以下载

封装方法:

export const downLoadFetch = (conf, params, name, suffix) => {
  const par = JSON.stringify(params) == '{}' ? '' : `?${qs.stringify(params)}`
  axios({
    method: 'get',
    url: `${conf.url}${par}`,
    responseType: 'blob',
  })
    .then(response => {
      if (!response.data) return
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = window.URL.createObjectURL(new Blob([response.data]))
      link.setAttribute('download', `${name || 'export'}.${suffix || 'xls'}`)
      document.body.appendChild(link)
      link.click()
    })
    .catch(console.error)
}

downLoadFetch = (conf, params, name, suffix)

四个参数分别代表:接口,需要给接口传的参数,文件名,文件后缀

使用:先页面引入,然后调用

downLoadFetch(this.$billURL.downloadExcel(), '', '文件名')   


2,input框验证及使用方法

限制及使用方法一(当输入正确时才可提交):

位置(和import同级)

 const regTel = /^1(2|3|4|5|6|7|8|9)\d{9}$/;//手机号验证

const regTel = /^[0][0-9]{2,3}-[0-9]{5,10}$/;//座机号验证

使用方式:

 限制及使用方法二(在输入时就开始限制,也就是无法输入错误的):

下面是限制只能输数字以及小数点后两位

          <el-input
            v-model.trim="input"
            placeholder="请输入内容"
            size="mini"
            :maxlength="13"
            @input="
              (v) =>
                (input = v
                  .replace(/[^\d.]/g, '')
                  .replace(/^0{1,}/g, '')
                  .replace(/\.{2,}/g, '.')
                  .replace(/^\./g, '')
                  .replace('.', '$#$')
                  .replace(/\./g, '')
                  .replace('$#$', '.')
                  .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'))
            "
          ></el-input>

3,数组对象根据某个key值去重

封装:

// 数组去重
export function unique(arr, key) {
  const res = new Map()
  return arr.filter(arr => !res.has(arr[key]) && res.set(arr[key], 1))
}

 页面调用(记得先在页面引入):


4,input 框阻止默认回车换行

html:

            <el-input
              v-model="scope.row.categoryGoalName"
              placeholder="请输入"
              v-if="!disabled"
              type="textarea"
              :rows="1"
              autosize
              @keydown.enter.native="textareaKeydown"
            />

方法:

    textareaKeydown() {
      let e = window.event || arguments[0];
      if (e.key == "Enter" || e.code == "Enter" || e.keyCode == 13) {
        e.returnValue = false;
        return false;
      }
    },

5,数据上移下移

//this.mapTableData  数据源
//index  当前行索引
handleChangeItem(index, type) {
    if (type == "up") {
      let upData = this.mapTableData[index - 1];
      this.mapTableData.splice(index - 1, 1);
      this.mapTableData.splice(index, 0, upData);
    } else {
      let downData = this.mapTableData[index + 1];
      this.mapTableData.splice(index + 1, 1);
      this.mapTableData.splice(index, 0, downData);
    }
},

6,a标签下载文件,并自定义文件名

    down(url, fileName) {
      var xhr = new XMLHttpRequest()
      xhr.open('get', url, true)
      xhr.responseType = 'blob'
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
          if (xhr.status == 200) {
            var oA = document.createElement('a')
            var href = window.URL.createObjectURL(xhr.response)
            oA.href = href
            oA.download = fileName
            oA.style.display = 'none'
            document.body.appendChild(oA)
            oA.click()
            document.body.removeChild(oA)
            window.URL.revokeObjectURL(href)
          } else {
            console.log('请求状态错误', xhr.status)
          }
        }
      }
      xhr.send()
    }

7,随机生成具有唯一性的字符串方法

    soleString32() {
      var str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
      var timestamp = +new Date() + Math.floor(Math.random() * 10)
      var resultStr = ''

      for (var i = 0; i < 19; i++) {
        resultStr += str.charAt(Math.floor(Math.random() * str.length))
      }
      resultStr += timestamp

      resultStr = resultStr.split('')
      resultStr.sort(function (a, b) {
        return Math.random() - 0.5
      })
      resultStr = resultStr.join('')
      return resultStr
    }

8,转化时间戳

export default function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, `${date.getFullYear()}`.substr(4 - RegExp.$1.length))
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = `${o[k]}`
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : `00${str}`.substr(str.length))
    }
  }

  return fmt
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值