utils

/**
 * 是否是数字
 * @param {any} n
 */
export const validateNumber = (n: any) =>
  !isNaN(parseFloat(n)) && isFinite(n) && Number(n) === n

/**
 * 保留两位小数、千分位格式化,格式:12,345.67
 * @param {string|number} amount
 * @returns {string}
 */
export const formatAmount = (amount: any) => {
  if (!validateNumber(+amount)) {
    return amount
  }
  return (+amount).toFixed(2).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')
}



// 删除url中某个参数
const funcUrlDel = (loca, name) => {
  let baseUrl = ''
  if (loca.indexOf('&') > -1) {
    baseUrl = loca.split('?')[0] + '?'
  } else {
    baseUrl = loca.split('?')[0]
  }
  let query = loca.split('?')[1]
  if (query && query.indexOf(name) > -1) {
    var obj = {}
    var arr = query.split('&')
    for (var i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split('=')
      obj[arr[i][0]] = arr[i][1]
    }
    delete obj[name]
    var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g, '').replace(/\:/g, '=').replace(/\,/g, '&')
    return url
  } else {
    return loca
  }
}




/**
 * 获取Url参数中指定name的值
 * @param name 参数名称
 * @returns {string}
 */
export const getURLParam = (name: string) => {
  const re = new RegExp('(^|&)' + name + '=([^&#]*)(&|$)')
  let value = ''
  const arrHash = window.location.hash.split('?')
  const arrSearch = window.location.search.substr(1).split('?')
  arrHash.shift()
  const arr = arrSearch.concat(arrHash)

  for (let i = 0; i < arr.length; i++) {
    const r = arr[i].match(re)
    if (r !== null && r[2]) {
      value = r[2]
      break
    }
  }
  return value
}

###  延时函数
export const sleep = function(delay: number) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      try {
        resolve(1)
      } catch (e) {
        reject(0)
      }
    }, delay)
  })
}
/**
 * rem 换算 px
 * @param rem 设计稿rem值
 * @returns {number} px值
 */
export const rem2px = (rem: any) => {
  const rootFontSize = parseFloat(
    window.document.documentElement.style.fontSize
  )
  return parseFloat(rem) * rootFontSize
}

平滑滚动

const scrollToTop = ()  => {
       const c = document.documentElement.scrollTop || document.body.scrollTop;
        if (c > 0) {
          window.requestAnimationFrame(scrollToTop);
          window.scrollTo(0, c - c / 8);
        }
    }

正则去掉括号

cosnt nstr = str.replace(/\([^\)]*\)/g,"")

  • js编译、解析Urlencode
1、编码
var str  = encodeURIComponent('中文');
2、解码
var str  = decodeURIComponent(UrlEncode);

替换中文逗号

    this.skuIds = this.skuIds.replace(/,/ig,',')

移动端弹窗去掉滚动条

public onShowChange(value: boolean) {
    if (value) {
      document.documentElement.style.position = 'fixed'
      document.body.style.overflow = 'hidden'
      document.body.addEventListener(
        'touchmove',
        event => {
          event.preventDefault()
        },
        false
      )
    } else {
      document.documentElement.style.position = 'static'
      document.body.style.overflow = 'auto'
      document.body.removeEventListener(
        'touchmove',
        event => {
          event.preventDefault()
        },
        false
      )
    }


### 下载
handleFileStreamExcel(res, fileName) {
      const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = fileName + '.xlsx' // 下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
    },
    handleFileStreamCsv(res, fileName) {
      const blob = new Blob([res], { type: 'text/csv' })
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = fileName + '.csv' // 下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
    }

兼容安卓input唤起键盘

(function (window,document) {
    document.querySelector('input[type="text"]').addEventListener('focus',function (e) {
     setTimeout(function () {
         var docHeight = window.innerHeight;
         var bottom = e.target.getBoundingClientRect().bottom
         var scrollHeight = bottom-docHeight
         if(scrollHeight>0){
             document.body.scrollTop =  scrollHeight+document.body.scrollTop+10
         }
     },400)
    },false)
})(window,document)

判断当前是安卓设备还是ios

const u = navigator.userAgent
// 安卓
export const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
// IOS
export const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

/**

  • 兼容安卓键盘
    */
export const androidKeyboardInit = () => {
  const u = navigator.userAgent
  const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
  if (isAndroid) {
    document.querySelector('input[type="text"],input[type="password"]').addEventListener('focus', function (e) {
      setTimeout(function () {
        var docHeight = window.innerHeight
        var bottom = e.target.getBoundingClientRect().bottom
        var scrollHeight = bottom - docHeight
        if (scrollHeight > 0) {
          document.body.scrollTop = scrollHeight + document.body.scrollTop + 10
        }
      }, 400)
    }, false)
  }
}


/**
 * 兼容安卓键盘
 */
export const androidKeyboardInit = () => {
  const u = navigator.userAgent
  const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
  if (isAndroid) {
    window.addEventListener('resize', () => {
      const activeElement = document.activeElement
      if (activeElement.tagName === 'INPUT' ||
          activeElement.tagName === 'TEXTAREA') {
        setTimeout(() => {
          activeElement.scrollIntoView()
        }, 100)
      }
    })
  }
}

pc跳转移动端

if( window.location.search.indexOf("?via=")<0 &&
                ( /Android|Windows Phone|iPhone|iPod/i.test(navigator.userAgent)  || /AppleWebKit.*Mobile/i.test(navigator.userAgent) )
          ){
                try{
                    if(/Android|iPhone|Windows Phone|webOS|iPod|BlackBerry/i.test(navigator.userAgent)){
                        var referrer = document.referrer;
                        if (referrer && referrer !== "") {
                          referrer += referrer.indexOf("?") > -1 ? "&pcjump=1" : "?pcjump=1";
                        } else {
                          referrer = "none";
                        }
                        if (document.cookie) {
                          var date = new Date();
                          date.setDate(date.getDate() + 1);
                          document.cookie = "PC2MRealRef=" + escape(referrer) + ";expires=" + date.toUTCString() + "; domain=.zol.com.cn; path=/";
                        }
                        window.location.href="xxx/mobile/";
                    }
                }catch(e){}

解析excel 流文件 拦截器参数配置 responseType: 'blob'

function downLoadxlsx (excelTitle = 1, blobData = '') {
      if (!blobData) return false
      const url = window.URL.createObjectURL(new Blob([blobData], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', excelTitle + '.xlsx')
      document.body.appendChild(link)
      link.click()
    }

// 对象去重
    Array.prototype.unique = function (key = '') {
      const arr = this || []
      if (!arr || !arr.length) return []
      let newArr = []
      arr.forEach(item => {
        const filterLists = newArr.filter(ele => {
          return ele[key] === item[key]
        })
        if (filterLists && !filterLists.length) newArr.push(item)
      })
      return newArr
    }
// 统计数量
Array.prototype.statistics = function () {
      const _arr = this || []
      return _arr.reduce((result, item) => {
        result[item] = result.hasOwnProperty(item) ? ++result[item] : 1
        return result
      }, {})
    }
// 取最大的对象
Array.prototype.maxNum = function () {
      const _arr = this || []
      const _obj = _arr.reduce((result, item) => {
        result[item] = result.hasOwnProperty(item) ? ++result[item] : 1
        return result
      }, {})
      const key = Object.keys(_obj).find(
        item => Math.max(...Object.values(_obj)) === _obj[item]
      )
      return { label: key, num: _obj[key] }
    }


export const to = (promise) => {
  return promise
    .then(data => [data, null])
    .catch(err => [undefined, err])
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容