MENU

嘿! 这是一篇前端小心得~

• July 6, 2020 • Read: 304 • Web Program

说一下最近公司项目的需求实现方式

视频预加载与本地化

如果页面有若干个视频,我们想做到页面刚进来的时候就把所有的视频缓存在本地,下次进页面就可以直接读取缓存而不是向服务器重复请求。

实现方法

const saveVideo = src => {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest()
    xhr.open('GET', src, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
      if (this.status === 200) {
        const videoBlob = this.response;
        const blobSrc = URL.createObjectURL(videoBlob); // IE10+
        resolve(blobSrc)
      }
    };
    xhr.send();
  })
};

使用

saveVideo(`xxxx.mp4`).then(res=>console.log(res))

监听localStorage变化

需要重写 window.localStorage.setItem()

  var orignalSetItem = localStorage.setItem;
  window.localStorage.setItem = function(key,newValue){
      var setItemEvent = new Event("setItemEvent");
      setItemEvent.key = key;
      setItemEvent.newValue = newValue;
      window.dispatchEvent(setItemEvent);
      orignalSetItem.apply(this,arguments);
  };

使用

window.addEventListener("setItemEvent", function(){console.log(e)})
window.localStorage.setItem(name, value)//console.log(e)

给你的React 加上动画

npm i animate.css -S

使用

import 'animate.css'
<div className={`animate__animated animate__fadeInLeft`}>云屏编号:100006</div>

这样就可以了。

更多效果请参阅 animate.css

图片未加载完成添加loading画面

{
  test.boxList.data.map(item => {
    return (
            <div onClick={() => GotoDetail(item)} key={item.image} className={`${styles.imgbox}                                         animate__animated animate__fadeInUp`}>
                    <img className='imgLoading' src-data={item.image} alt="" /> //关键部分
                    </div>
                    )
    })
}

方法

//判断浏览器
  var Browser = new Object();
  Browser.userAgent = window.navigator.userAgent.toLowerCase();
  Browser.ie = /msie/.test(Browser.userAgent);
  Browser.Moz = /gecko/.test(Browser.userAgent);
  window.Imagess = (url, callback, error) => {
    var val = url;
    var img = new Image();
    if (Browser.ie) {
      img.onreadystatechange = function () {
        if (img.readyState == "complete" || img.readyState == "loaded") {
          callback(img);
        }
      }
    } else {
      img.onload = function () {
        if (img.complete == true) {
          callback(img);
        }
      }
    }
    //如果因为网络或图片的原因发生异常,则显示该图片
    if (error) {
      img.onerror = error;

    } else {
      img.onerror = function () {
        img.src = imgloading
      }
    }
    img.src = val;
  }
  
  //调用方法 
  
let imglist = document.querySelectorAll('.imgLoading')
for (let i = 0; i < imglist.length; i++) {
     let tt = imglist[i];
     //防止重复加载
      if (tt.loading == true) {
           continue;
       }
       //没有该属性代表不加载
       if (!tt.getAttribute("src-data")) {
                 continue;
        }
        tt.loading = true;
        tt.src = ’loading‘;//这里写上未加载出来之前显示的内容
        window.Imagess(tt.getAttribute("src-data"), function (obj) {
        tt.src = obj.src;
        tt.removeAttribute("src-data");
        });
}
  

Antd 表格导出为Excel

/*
 * @Author: XiaoHuwei
 * @Date: 2020-07-10 10:16:16
 * @LastEditors: XiaoHuwei
 * @LastEditTime: 2020-07-10 10:33:57
 * @FilePath: /screen-cloud-bg/src/utils/Export.js
 * @Description: Global export for Exel function 
 */ 
import { File } from 'better-xlsx';
import { saveAs } from 'file-saver';

const ExportExcel = (column, dataSource, fileName = 'example')=> {
  // 新建工作谱
  const file = new File();
  // 新建表
  let sheet = file.addSheet('sheet-test');
  // 获取表头行数
  let depth = getDepth(column);
  // 获取表头的列数
  let columnNum = getColumns(column);
  // 新建表头行数
  let rowArr = [];
  for (let k = 0; k < depth; k++) {
    rowArr.push(sheet.addRow());
  }
  // 根据列数填充单元格
  rowArr.map(ele => {
    for (let j = 0; j < columnNum; j++) {
      let cell = ele.addCell();
      cell.value = j;
    }
  });
  // 初始化表头
  init(column, 0, 0);
  // 按顺序展平column
  let columnLineArr = [];
  columnLine(column);
  // 根据column,将dataSource里面的数据排序,并且转化为二维数组
  let dataSourceArr = [];
  dataSource.map(ele => {
    let dataTemp = [];
    columnLineArr.map(item => {
      dataTemp.push({
        [item.dataIndex]: ele[item.dataIndex],
        value: ele[item.dataIndex],
      });
    });
    dataSourceArr.push(dataTemp);
  });
  // debugger;
  // 绘画表格数据
  dataSourceArr.forEach((item, index) => {
    //根据数据,创建对应个数的行
    let row = sheet.addRow();
    row.setHeightCM(0.8);
    //创建对应个数的单元格
    item.map(ele => {
      let cell = row.addCell();
      if (ele.hasOwnProperty('num')) {
        cell.value = index + 1;
      } else {
        cell.value = ele.value;
      }
      cell.style.align.v = 'center';
      cell.style.align.h = 'center';
    });
  });
  //设置每列的宽度
  for (var i = 0; i < 4; i++) {
    sheet.col(i).width = 20;
  }
  file.saveAs('blob').then(function(content) {
    saveAs(content, fileName + '.xlsx');
  });

  // 按顺序展平column
  function columnLine(column) {
    column.map(ele => {
      if (ele.children === undefined || ele.children.length === 0) {
        columnLineArr.push(ele);
      } else {
        columnLine(ele.children);
      }
    });
  }
  // 初始化表头
  function init(column, rowIndex, columnIndex) {
    column.map((item, index) => {
      let hCell = sheet.cell(rowIndex, columnIndex);
      // 如果没有子元素, 撑满列
      if (item.title === '操作') {
        hCell.value = '';
        return;
      } else if (item.children === undefined || item.children.length === 0) {
        // 第一行加一个单元格
        hCell.value = item.title;
        hCell.vMerge = depth - rowIndex - 1;
        hCell.style.align.h = 'center';
        hCell.style.align.v = 'center';
        columnIndex++;
        // rowIndex++
      } else {
        let childrenNum = 0;
        function getColumns(arr) {
          arr.map(ele => {
            if (ele.children) {
              getColumns(ele.children);
            } else {
              childrenNum++;
            }
          });
        }
        getColumns(item.children);
        hCell.hMerge = childrenNum - 1;
        hCell.value = item.title;
        hCell.style.align.h = 'center';
        hCell.style.align.v = 'center';
        let rowCopy = rowIndex;
        rowCopy++;
        init(item.children, rowCopy, columnIndex);
        // 下次单元格起点
        columnIndex = columnIndex + childrenNum;
      }
    });
  }
  // 获取表头rows
  function getDepth(arr) {
    const eleDepths = [];
    arr.forEach(ele => {
      let depth = 0;
      if (Array.isArray(ele.children)) {
        depth = getDepth(ele.children);
      }
      eleDepths.push(depth);
    });
    return 1 + max(eleDepths);
  }

  function max(arr) {
    return arr.reduce((accu, curr) => {
      if (curr > accu) return curr;
      return accu;
    });
  }
  // 计算表头列数
  function getColumns(arr) {
    let columnNum = 0;
    arr.map(ele => {
      if (ele.children) {
        getColumns(ele.children);
      } else {
        columnNum++;
      }
    });
    return columnNum;
  }
}

export default ExportExcel;
Last Modified: July 10, 2020
Archives QR Code Tip
QR Code for this page
Tipping QR Code
Leave a Comment

已有 1 条评论
  1. 我的评论又不行了