前端工具函数

78 阅读1分钟

Vue 获取组件的名字(name)

function getComponentName() {
    let currentMatched = router.currentRoute.value.matched;
    let currentComponent = currentMatched[currentMatched.length - 1].components!.default;
    let componentName = currentComponent.name || (currentComponent as { __name: string }).__name;
    
    return componentName;
}

判断汉字

MDN

!!'汉字'.match(/\p{Script=Han}/u)

window.open弹窗拦截

const btn = document.querySelector('button')
btn.addEventListener('click', function () {
    const newPage = window.open(); // 打开一个不被拦截的空白窗口
    axios.get('/api').then(res => {
        newPage.location.href = '/test.html' // 修改空白窗口的url
    })
})

返回顶部

/**
* 基于 requestAnimationFrame 的返回顶部
* @param {HTMLDivElement} dom 目标DOM
* @param {Number} destination 滚动位置
* @param {Number} rate 缓动速率
* @param {Function} callback 动画结束回调
*/
export const backTop = (dom: HTMLElement, destination: number = 0, rate: number = 5, callback: Function) => {
  let position = dom?.scrollTop
  if (!position || position === destination || typeof destination !== 'number') return false
  // 不存在原生requestAnimationFrame 用setTimeout模拟替代 按60Hz的显示器算刷新间隔16.67~17
  if (!window.requestAnimationFrame) {
    window.requestAnimationFrame = function (fn) {
      return setTimeout(fn, 17)
    }
  }

  const step = () => {
    position = position + (destination - position) / rate
    if (Math.floor(position) === destination) {
      callback && callback()
      return
    }

    dom.scrollTo(0, position)
    requestAnimationFrame(step)
  }
  step()
}

PC 无限滚动

    load() {
      let _scroll = () => {
        let bottomOfWindow = document.documentElement.scrollTop + document.documentElement.clientHeight === document.body.scrollHeight;

        if (bottomOfWindow) {
          if (this.projects.length >= this.total) {
            return;
          }
          this.searchParams.current++;
          let params = JSON.parse(JSON.stringify(this.searchParams));
          this.$axios.$get('/api/project/projectList', {
            params: filterNullValue(params)
          }).then((res) => {
            if (res.code == 200) {
              this.projects.push(...res.data.records);
              this.total = res.data.total;
            }
          });
        }
      };
      _scroll();
    },
    scroll() {
      window.addEventListener('scroll', this.load);
    },
    
    destroyed() {
      window.removeEventListener('scroll', this.load);
    },

点击下载Blob文件

export const downloadBlob = (blob: Blob | MediaSource, fileName: string) => {
  const blobURL = URL.createObjectURL(blob);

  const downloadLink = document.createElement('a');
  downloadLink.href = blobURL;
  downloadLink.download = fileName;

  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
};