Javascript积累工具箱

60 阅读1分钟
防抖
export const debounce = (fn, delay) => {

  let timer = null

  return function () {

    const context = this

    const arg = arguments

    clearTimeout(timer)

    timer = setTimeout(function () {

      fn.apply(context, arg)

    }, delay)

  }

}
节流
export const throttle = (fn, delay = 100) => {

  let prevTime = Date.now()

  return function () {

    const curTime = Date.now()

    if (curTime - prevTime > delay) {

      fn.apply(this, arguments)

      prevTime = curTime

    }
  }
}
URL地址拆解拆解
export const urlParse = url => {
      var temp = {
        default: url,     // 默认地址
        deal: '',     // 协议
        origin: '',
        originAndPath: '',
        path: '',
        search: '',
        searchData: '',
        hash: '',
        query: '',
        queryData: '',
        hashPath: ''
      }
  
      var left = ''
      if (url.lastIndexOf('#') !== -1) {
        left = url.slice(0, url.lastIndexOf('#'))
        temp.hash = url.slice(url.lastIndexOf('#'))
      } else {
        left = url
      }

      var paramsToObj = params => {
        var obj = {}
        var searchArr = params.split('&')
        searchArr.forEach(v => {
          var index = v.indexOf('=')
          if (index !== -1) {
            var name = v.substring(0, index)
            var val = v.substring(index + 1, v.length)
            obj[name] = val
          }
        })
        return obj
      }

      if (left.indexOf('?') !== -1) {
        temp.search = left.slice(left.lastIndexOf('?'))
        temp.searchData = paramsToObj(temp.search.replace('?', ''))
        temp.originAndPath = left.slice(0, left.lastIndexOf('?'))
      } else {
        temp.originAndPath = left
      }

      var originAndPathSplit0 = temp.originAndPath.split('//')
      temp.deal = originAndPathSplit0[0]
      var originAndPathSplit1 = originAndPathSplit0[1]
      var pathSplit = originAndPathSplit1.split('/')
      temp.origin = temp.deal + '//' + pathSplit[0]
      for (var i = 1; i < pathSplit.length; i++) {
        if (pathSplit[i]) {
          temp.path += '/' + pathSplit[i]
        }
      }

      if (temp.hash) {
        if (temp.hash.indexOf('?') !== -1) {
          temp.query = temp.hash.slice(temp.hash.indexOf('?'))
          temp.queryData = paramsToObj(temp.query.replace('?', ''))
          temp.hashPath = temp.hash.slice(0, temp.hash.indexOf('?'))
        } else {
          temp.hashPath = temp.hash
        }
      }
      return temp
}
文件下载
  axios({
    url,
    method: 'get',
    responseType: 'blob'
  }).then((res) => {
    const blob = new Blob([res.data], { type: 'application/pdf' })
    const href = URL.createObjectURL(blob) // 创建新的URL表示指定的blob对象
    const a = document.createElement('a') // 创建a标签
    a.style.display = 'none'
    a.href = href // 指定下载链接
    a.download = `${Date.now()}.pdf` // 必须指定下载文件名
    a.click() // 触发下载
    URL.revokeObjectURL(a.href) // 释放URL对象
  })
  
const a = document.createElement('a')
a.download = `job_${new Date().getTime()}.xlsx`
a.href = window.URL.createObjectURL(data)
document.body.appendChild(a)
a.click()
a.remove()
打开新页面
    export function toBlank(path, query = {}) {
      const href = location.origin + path + '?' + qs.stringify(query)
      const oA = document.createElement('a')
      oA.style.display = 'none'
      oA.href = href
      oA.target = '_blank'
      document.body.appendChild(oA)
      oA.click()
    }
一键置顶
handelTop() {
  const setTop = () => {
    const scrollTop = oSteps.scrollTop
    if (scrollTop > 0 )  {
      oSteps.scrollTop = parseInt(oSteps.scrollTop) * 0.6
      setTimeout(() => {
        setTop()
      }, 50)
    } else {
      oSteps.scrollTop = 0
    }
  }
  setTop()
},
上拉加载
handelInitScroll() {
  setTimeout(() => {
    const oTabsle = document.querySelector('拥有滚动条的元素')
    oTabsle.addEventListener('scroll', (event) => {
      const scrollTop = event.target.scrollTop
      const clientHeight = event.target.clientHeight
      const scrollHeight = event.target.scrollHeight
      if (scrollTop + clientHeight >= scrollHeight - 50) {
        clearTimeout(this.setTimer)
        this.setTimer = setTimeout(() => {
          if (this.loadList) {
            return
          }
          this.refresh()
          this.loadList = true
          this.loading = true
        }, 200)
      }
    })
  }, 100)
},