我的笔记

360 阅读8分钟

1.图片设置宽高失真处理

img {
  image-rendering: -moz-crisp-edges; /* Firefox */ 
  image-rendering: -o-crisp-edges; /* Opera */ 
  image-rendering: -webkit-optimize-contrast; /*Webkit (non-standard naming) */
  image-rendering: crisp-edges; 
  -ms-interpolation-mode: nearest-neighbor; /* IE (non-standard property) */
}

2.img标签使用object-fit时在IE上的解决方法

肯定的是这个不是唯一的方法。只是本人在实际项目中的一个解决方法。 众所周知,object-fit是个非常好的CSS3属性,可以将各种元素相对父级进行contain/cover操作。 尤其做响应式网站的时候非常好用。但问题是IE不支持。 那么针对IE,下面有个方法:

原理:判断如果是IE,将图片赋给父级元素作为背景,然后将图片移除。以达到在IE上使用background-size时有跟object-fit同样的效果。

用法:

DOM结构大概是:

<div class="hasbg">
   <img src="">
</div>

js部分代码:

 function ieFix() {
    if (!!window.ActiveXObject || 'ActiveXObject' in window) {
        $('html').addClass('is-ie');
        if ($('.hasbg').length) {
            $('.hasbg').each(function () {
                var $this = $(this);
                var $src = $this.find('img').attr('src');
                if ($src.length) {
                    $this.css({
                        'background-image': function () {
                            $this.find('img').remove();
                            return 'url(' + $src + ')';
                        }
                    });
                }
            });
        }
    }
} 

可以看出,首先判断了有没有hasbg这样的一个class。 如果有,进一步执行代码。 如果是IE浏览器,它将会把img的图片赋给hasbg作为背景。而后将img移除。 到此,图片转移成背景的操作就完成了。

还差一点操作,就是对背景图片的位置进行适当操作。

样式可以是:

.hasbg {
    background-position: center center;
    background-attachment: scroll;
    background-size: contain;
    -webkit-background-size: contain;
    background-repeat: no-repeat;
}

3.水平广告滚动

html部分

<div id="scroll_div">
  <div id="scroll_begin">
    <span v-for="(item, index) in hornList" :key="index" class="horn-list-item">
      {{item.knowledgeName}}
    </span>
  </div>
  <div id="scroll_end"></div>
</div>

js部分

scrollHornLeft() {
    var speed = 50
    var MyMar = null
    var scroll_begin = document.getElementById('scroll_begin')
    var scroll_end = document.getElementById('scroll_end')
    var scroll_div = document.getElementById('scroll_div')
    scroll_end.innerHTML = scroll_begin.innerHTML
    function Marquee() {
      if (scroll_end.offsetWidth - scroll_div.scrollLeft <= 0) {
        scroll_div.scrollLeft -= scroll_begin.offsetWidth
      } else {
        scroll_div.scrollLeft++
      }
    }
    MyMar = setInterval(Marquee, speed)
    // 鼠标点击这条公告栏的时候,清除上面的方法,让公告栏暂停
    scroll_div.onmouseover = function() {
      clearInterval(MyMar)
    }
    // 鼠标点击其他地方的时候,公告栏继续运动
    scroll_div.onmouseout = function() {
      MyMar = setInterval(Marquee, speed)
    }
 }

css部分

#scroll_div {
  height: 40px;
  line-height: 40px;
  overflow: hidden;
  white-space: nowrap;
  width: 1200px;
  margin: 0 auto;
  // color: #999999;
  text-align: center;
}
#scroll_begin,
#scroll_end {
  display: inline;
}
.horn-list-item {
  margin-right: 20px;
}
.horn-list-icon {
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: #6caae4;
  margin-right: 5px;
  vertical-align: middle;
}

4.前端生成二维码下载

<vue-qr :text="qrcode.url" :margin="0" colorDark="#0088e1" colorLight="#fff" :size="200" class="survey_qrcode" ref="qrcode"></vue-qr>

import vueQr from 'vue-qr'

const filename = '活动二维码.png'
const url = this.$refs.qrcode.$el.src
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()

5.js获取富文本html代码中图片地址

function getimgsrc(html='') { 
  var reg = /<img.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/gim; 
  var arr = []; 
  while (tem = reg.exec(html)) { 
    arr.push(tem[2]); 
  } 
  return arr; 
}

getImgSrc(richtext='') {
  let imgList = [];
  richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
    imgList.push(capture);
  });
  return imgList;
}

6.JS将下划线转驼峰

const replaceUnderLine = (val, char = '_') => {
  const arr = val.split('')
  const index = arr.indexOf(char)
  arr.splice(index, 2, arr[index+1].toUpperCase())
  val = arr.join('')
  return val
}
console.log(replaceUnderLine('test_prop')) // testProp

const  filterUnderLine = (obj, char = '_') => {
  const arr =  Object.keys(obj).filter(item => item.indexOf(char) !== -1)
  arr.forEach(item => {
    const before = obj[item]
    const key = replaceUnderLine(item)
    obj[key] = before
    delete obj[item]
  })
  return obj
}
console.log(filterUnderLine({test_name: 'frank'})) // { testName: 'frank }

function strToCamel(str){
    return str.replace(/(^|_)(\w)/g,(m,$1,$2)=>$2.toUpperCase());
}
console.log(strToCame('aa_bb_cc_d_e_f'))     //  AaBbCcDEF

7.html2canvas 填坑之路

1.html2canvas截屏在H5微信移动端踩坑,ios和安卓均可显示

2.html2canvas生成图片出现白边儿的解决方法

8.使用背景渐变实现效果

微信图片_20210311110401.png 微信图片_20210311110401.png

9.数组按照指定长度切割

const data = [
    {name:'小赵',value:'12'},
    {name:'小钱',value:'12'},
    {name:'小孙',value:'12'},
    {name:'小李',value:'12'},
    {name:'小周',value:'12'},
    {name:'小吴',value:'12'},
    {name:'小郑',value:'12'},
    {name:'小王',value:'12'},
    {name:'小付',value:'12'},
    {name:'小张',value:'12'}
]
console.log(data);
const FunData = (arr = [], num=3)=>{
    let proportion = num; //按照比例切割
    let index = 0;
    let _data =[];
    for(let i=0;i<arr.length;i++){
        if(i % proportion === 0 && i !== 0){
            _data.push(arr.slice(index,i));
            index = i;
        }
        if((i+1) === arr.length){
            _data.push(arr.slice(index,(i+1)));
        }
    }
    return _data;
}
console.log(FunData(data));

10.BFC

BFC 定义
BFC(Block formatting context)直译为"块级格式化上下文"。它是一个独立的渲染区域,只有Block-level box参与, 它规定了内部的Block-level Box如何布局,并且与这个区域外部毫不相干。

在解释什么是BFC之前,我们需要先知道BoxFormatting Context的概念。

Box:css布局的基本单位
BoxCSS 布局的对象和基本单位, 直观点来说,就是一个页面是由很多个 Box 组成的。元素的类型和 display 属性,决定了这个 Box 的类型。 不同类型的 Box, 会参与不同的 Formatting Context(一个决定如何渲染文档的容器),因此Box内的元素会以不同的方式渲染。让我们看看有哪些盒子:

block-level box:display 属性为 block, list-item, table 的元素,会生成 block-level box。并且参与 block fomatting context;
inline-level box:display 属性为 inline, inline-block, inline-table 的元素,会生成 inline-level box。并且参与 inline formatting context;
run-in box: css3 中才有, 这儿先不讲了。
Formatting Context
Formatting context 是 W3C CSS2.1 规范中的一个概念。它是页面中的一块渲染区域,并且有一套渲染规则,它决定了其子元素将如何定位,以及和其他元素的关系和相互作用。最常见的 Formatting context 有 Block fomatting context (简称BFC)和 Inline formatting context (简称IFC)。

BFC是一个独立的布局环境,其中的元素布局是不受外界的影响,并且在一个BFC中,块盒与行盒(行盒由一行中所有的内联元素所组成)都会垂直的沿着其父元素的边框排列。

BFC的布局规则
内部的Box会在垂直方向,一个接一个地放置。

Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠。

每个盒子(块盒与行盒)的margin box的左边,与包含块border box的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如此。

BFC的区域不会与float box重叠。

BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。

计算BFC的高度时,浮动元素也参与计算。

如何创建BFC
1、float的值不是none。
2、position的值不是static或者relative。
3、display的值是inline-block、table-cell、flex、table-caption或者inline-flex
4、overflow的值不是visible
BFC的作用
1.利用BFC避免margin重叠。
一起来看一个例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>防止margin重叠</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    p {
        color: #f55;
        background: yellow;
        width: 200px;
        line-height: 100px;
        text-align:center;
        margin: 30px;
    }
</style>
<body>
    <p>看看我的 margin是多少</p>
    <p>看看我的 margin是多少</p>
</body>
</html>
页面生成的效果就是这样的:

根据第二条,属于同一个BFC的两个相邻的Box会发生margin重叠,所以我们可以设置,两个不同的BFC,也就是我们可以让把第二个p用div包起来,然后激活它使其成为一个BFC

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>防止margin重叠</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    p {
        color: #f55;
        background: yellow;
        width: 200px;
        line-height: 100px;
        text-align:center;
        margin: 30px;
    }
    div{
        overflow: hidden;
    }
</style>
<body>
    <p>看看我的 margin是多少</p>
    <div>
        <p>看看我的 margin是多少</p>
    </div>
</body>
</html>

2.自适应两栏布局
根据:

每个盒子的margin box的左边,与包含块border box的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如此。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    body {
        width: 100%;
        position: relative;
    }
 
    .left {
        width: 100px;
        height: 150px;
        float: left;
        background: rgb(139, 214, 78);
        text-align: center;
        line-height: 150px;
        font-size: 20px;
    }
 
    .right {
        height: 300px;
        background: rgb(170, 54, 236);
        text-align: center;
        line-height: 300px;
        font-size: 40px;
    }
</style>
<body>
    <div class="left">LEFT</div>
    <div class="right">RIGHT</div>
</body>
</html>

页面:


又因为:

BFC的区域不会与float box重叠。
所以我们让right单独成为一个BFC

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    body {
        width: 100%;
        position: relative;
    }
 
    .left {
        width: 100px;
        height: 150px;
        float: left;
        background: rgb(139, 214, 78);
        text-align: center;
        line-height: 150px;
        font-size: 20px;
    }
 
    .right {
        overflow: hidden;
        height: 300px;
        background: rgb(170, 54, 236);
        text-align: center;
        line-height: 300px;
        font-size: 40px;
    }
</style>
<body>
    <div class="left">LEFT</div>
    <div class="right">RIGHT</div>
</body>
</html>

页面:


right会自动的适应宽度,这时候就形成了一个两栏自适应的布局。

3.清楚浮动。
当我们不给父节点设置高度,子节点设置浮动的时候,会发生高度塌陷,这个时候我们就要清楚浮动。

比如这样:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>清除浮动</title>
</head>
<style>
    .par {
        border: 5px solid rgb(91, 243, 30);
        width: 300px;
    }
    
    .child {
        border: 5px solid rgb(233, 250, 84);
        width:100px;
        height: 100px;
        float: left;
    }
</style>
<body>
    <div class="par">
        <div class="child"></div>
        <div class="child"></div>
    </div>
</body>
</html>

页面:

这个时候我们根据最后一条:

计算BFC的高度时,浮动元素也参与计算。
给父节点激活BFC

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>清除浮动</title>
</head>
<style>
    .par {
        border: 5px solid rgb(91, 243, 30);
        width: 300px;
        overflow: hidden;
    }
    
    .child {
        border: 5px solid rgb(233, 250, 84);
        width:100px;
        height: 100px;
        float: left;
    }
</style>
<body>
    <div class="par">
        <div class="child"></div>
        <div class="child"></div>
    </div>
</body>
</html>
页面:


总结
以上例子都体现了:

BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。

因为BFC内部的元素和外部的元素绝对不会互相影响,因此, 当BFC外部存在浮动时,它不应该影响BFC内部Box的布局,BFC会通过变窄,而不与浮动有重叠。同样的,当BFC内部有浮动时,为了不影响外部元素的布局,BFC计算高度时会包括浮动的高度。避免margin重叠也是这样的一个道理。
————————————————
版权声明:本文为CSDN博主「Leon_94」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sinat_36422236/article/details/88763187

11.eslint+prettier格式化代码

1.使用ESLint+Prettier来统一前端代码风格

12.Cannot assign to read only property 'exports' of object 解决方法

1.在babel中添加 sourceType: 'unambiguous'

13.图像相册重叠效果

<div
    class="image-box"
    :style="imageTranslate(subIndex, trailDataList[index][cameraIndex].cameraInfoList.length)"
    v-for="(subItem, subIndex) in trailDataList[index][cameraIndex].cameraInfoList"
    :key="subIndex"
  >
  </div>
                      
imageTranslate (index, len) {
  if (len === 1) return ''
  if (index < 3) {
    let flag = (2 - index) * 4
    let res = `transform: translate(${flag}px, ${flag}px)`
    if (index === 0) {
      res = `transform: translate(${flag}px, ${flag}px);box-shadow: 0 0 25px 0 rgba(0,0,0,0.20), 0 2px 4px 0 rgba(0,0,0,0.12);`
    }
    return res
  }
  return ''
}

14.CSS卡片效果

<ul class="search-wrap-tab-list">
    <li
      v-for="(item,index) in tabList"
      :key="index"
      class="search-wrap-tab-list-item"
      :class="{'actived':index===activedTab,'color-brand-border':index===activedTab&&isInputFocue}"
    >
      <span
        class="line"
        :class="{'actived':index===activedTab,'color-brand-border':index===activedTab&&isInputFocue}"
      ></span>
      <span class="text">{{item.value}}</span>
    </li>
  </ul>
.search-wrap-tab-list {
  position: relative;
  top: 1px;
  .search-wrap-tab-list-item {
    display: inline-block;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.7);
    letter-spacing: 0;
    text-align: center;
    line-height: 26px;
    padding: 0px 18px;
    border: 1px solid rgba(0, 0, 0, 0.3);
    transition: background-color 0.5s;
    position: relative;
    cursor: pointer;
    height: 26px;
    margin-right: 10px;
    border-right: none;
    border-bottom: none;
    background: #f5f5f6;
    z-index: 10;
    border-top-left-radius: 8px;
    border-top-right-radius: 4px;
    &.actived {
      z-index: 20;
      border-color: #b2b2b2;
      background-color: #fff;
      .line {
        border-color: #b2b2b2;
        background-color: #fff;
        border-bottom-color: #fff;
      }
    }
  }
  .line {
    position: absolute;
    border: none;
    z-index: -2;
    top: -1px;
    right: -10px;
    width: 18px;
    height: 26px;
    border-right: 1px solid rgba(0, 0, 0, 0.3);
    border-top: 1px solid rgba(0, 0, 0, 0.3);
    transform: skew(30deg);
    background: #f5f5f6;
    overflow: hidden;
    border-top-right-radius: 4px;
  }
}

15.js 鼠标、元素的距离属性

offsetTop //返回元素的上外缘距离最近采用定位父元素内壁的距离,如果父元素中没有采用定位的,则是获取上外边缘距离文档内壁的距离。

所谓的定位就是position属性值为relative、absolute或者fixed。返回值是一个整数,单位是像素。此属性是只读的。

offsetLeft //此属性和offsetTop的原理是一样的,只不过方位不同,这里就不多介绍了。

scrollLeft //此属性可以获取或者设置对象的最左边到对象在当前窗口显示的范围内的左边的距离,也就是元素被滚动条向左拉动的距离。

返回值是一个整数,单位是像素。此属性是可读写的。

scrollTop //此属性可以获取或者设置对象的最顶部到对象在当前窗口显示的范围内的顶边的距离,也就是元素滚动条被向下拉动的距离。

返回值是一个整数,单位是像素。此属性是可读写的。

//-------------------------------------------------------------------------------------------------

当鼠标事件发生时(不管是onclick,还是omousemove,onmouseover等)

clientX 鼠标相对于浏览器(这里说的是浏览器的有效区域)左上角x轴的坐标; 不随滚动条滚动而改变;

clientY 鼠标相对于浏览器(这里说的是浏览器的有效区域)左上角y轴的坐标; 不随滚动条滚动而改变;

pageX 鼠标相对于浏览器(这里说的是浏览器的有效区域)左上角x轴的坐标; 随滚动条滚动而改变;

pageY 鼠标相对于浏览器(这里说的是浏览器的有效区域)左上角y轴的坐标; 随滚动条滚动而改变;

screenX 鼠标相对于显示器屏幕左上角x轴的坐标;

screenY 鼠标相对于显示器屏幕左上角y轴的坐标;

offsetX 鼠标相对于事件源左上角X轴的坐标

offsetY 鼠标相对于事件源左上角Y轴的坐标

16.vue 启动报错:TypeError: Cannot read property ‘range‘ of null

1、在终端执行npm install babel-eslint@7.2.3 ,安装babel-eslint稳定版;

2、关闭项目,在本地删除node_modules文件夹,重新在编辑器打开项目;

3、执行npm install,初始化项目;

4、重新启动项目。

17.动态设置div中元素显示的个数

// 计算已选的内容
    calcShowNum () {
      this.$nextTick(() => {
        setTimeout(() => {
          const tagContainerWidth = this.$refs.tagContainer
            ? parseInt(window.getComputedStyle(this.$refs.tagContainer).width)
            : 0
          const tags = this.$refs.tag
          if (tags) {
            let tagWidths = 0
            let maxLength = 0
            for (let i = 0; i < tags.length; i++) {
              tagWidths +=
                parseInt(window.getComputedStyle(tags[i].$el).width) + 37
              if (tagWidths + 36 < tagContainerWidth) {
                maxLength = i + 1
              } else {
                break
              }
            }
            this.showLength = maxLength
            this.lastLength = this.valueClone.length - this.showLength
          }
        }, 0)
      })
    },

18.动态设置弹框距离在元素上的位子 上下左右

    position: absolute;
    document.body.appendChild(this.$refs['option-panel'])
    // 计算展示面板在左侧还是右侧,上侧还是下侧
    calcPosition (flag = false) {
      if (this.showPanel | flag) {
        const scrollTop =
          document.documentElement.scrollTop || document.body.scrollTop
        const scrollLeft =
          document.documentElement.scrollLeft || document.body.scrollLeft
        const clientHeight =
          document.documentElement.clientHeight || document.body.clientHeight
        const clientWidth =
          document.documentElement.clientWidth || document.body.clientWidth
        const eltop = this.$el.getBoundingClientRect().top
        const elbottom = this.$el.getBoundingClientRect().bottom
        const elLeft = this.$el.getBoundingClientRect().left
        const elRight = this.$el.getBoundingClientRect().right
        if (
          clientHeight - elbottom > this.panelHeight ||
          eltop < this.panelHeight + 4
        ) {
          // 面板在下方
          if (clientWidth - elLeft > this.panelWidth) {
            // 面板在左侧
            this.positionStyle = {
              left: elLeft + scrollLeft + 'px',
              top: elbottom + scrollTop + 4 + 'px'
            }
          } else {
            // 在右侧
            this.positionStyle = {
              left: elRight + scrollLeft - this.panelWidth + 'px',
              top: elbottom + scrollTop + 4 + 'px'
            }
          }
        } else {
          // 面板在上方
          if (clientWidth - elLeft > this.panelWidth) {
            // 面板在左侧
            this.positionStyle = {
              left: elLeft + scrollLeft + 'px',
              top: elbottom + scrollTop - 36 - this.panelHeight + 'px'
            }
          } else {
            // 在右侧
            this.positionStyle = {
              left: elRight + scrollLeft - this.panelWidth + 'px',
              top: elbottom + scrollTop - 36 - this.panelHeight + 'px'
            }
          }
        }
      }
    },

19.上下滚动跑马灯

HTML部分:

<%--放置上下滚动的消息--%>
<div class="messageWrap borderBox">
    <div class="message borderBox">
        <ul id="notice">
            <li class="text-ellipsis">这是一条消息0</li>
            <li class="text-ellipsis">这是一条消息1</li>
            <li class="text-ellipsis">这是一条消息2</li>
        </ul>
    </div>
</div>

css部分:

/* ============关于滚动消息的样式===========*/
.messageWrap{
  position:absolute;
  bottom:0;
  height:0.64rem;
  width:100%;
  padding:0 0.2rem;
  overflow:hidden;
}
.message{
  width:100%;
  background:#fff;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
  height:100%;
  overflow:hidden;
  padding-left:0.2rem;
}
.message li{
  line-height:0.64rem;
}
/*============关于滚动消息的样式=============*/

js部分:

//消息通知上下翻滚
var num=$("#notice").find("li").length;
if (num>1) {
    setInterval(function(){
        $('#notice').stop().animate({
            marginTop:"-26px"
        },500,function(){
            $('#notice').css({marginTop : "0"}).find("li:first").appendTo(this);
        });
    }, 3000);
}

19.对象数组去重

handleArr (arr = []) {
  const hash = {}
  const newArray = arr.reduce((item, next) => {
    // eslint-disable-next-line no-unused-expressions
    hash[next.id] ? '' : hash[next.id] = true && item.push(next)
    return item
  }, [])
  return newArray
}

19.隐藏任意数字中的位数变成*

hideInfo (number, type, percentage = 0.4) {
  // if (!info) return '--'
  // if (!this.isHideInfo) return info
  // if (type === 'phone') {
  //   let reg = /^(\d{3})\d{4}(\d{4})$/
  //   return info.replace(reg, '$1****$2')
  // } else if (type === 'idNumber') {
  //   let reg = /^(\d{6})\d{8}((\d{4})||(\d{3}\w{1}))$/
  //   return info.replace(reg, '$1********$2')
  // }
  if (!number) return '--'
  if (!this.isHideInfo) return number
  let length = number.length
  // 3位以下不隐藏
  if (length < 3) return number
  let hideLength = Math.round(length * percentage)
  let hideStart = Math.round(length * (1 - percentage) / 2) + 1
  return hideSensitiveText(number, hideStart, hideStart + hideLength - 1)
},
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

/**
 * @description: 隐藏敏感信息
 * @param str 需要处理的字符串
 * @param start 替换的起始位置
 * @param end 替换的截止位置
 * @param replaceStr 替换的字符串
 * @return 处理之后的字符串
 */
var hideSensitiveText = function hideSensitiveText(str, start, end) {
  var replaceStr = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '*';
  var subStrArr = str.split('');
  return [].concat(_toConsumableArray(subStrArr.slice(0, start - 1)), _toConsumableArray(subStrArr.slice(start - 1, end).fill(replaceStr)), _toConsumableArray(subStrArr.slice(end))).join('');
};

export default hideSensitiveText;

20.使用post/get方式下载

download (data, id) {
  const url = `data/export?id=` + id
  let xhr = new XMLHttpRequest()
  xhr.open('POST', url)
  xhr.setRequestHeader('Content-type', 'application/json')
  xhr.responseType = 'blob'
  xhr.send(JSON.stringify(data))
  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4 && xhr.status === 200) {
      let fileName = decodeURIComponent(
        xhr.getResponseHeader('content-disposition').split('=')[1]
      ).replace(/"/g, '')
      // let blob = new Blob(xhr.response, { type: contentTpye }); //ie10支持
      const padLocalUrl = URL.createObjectURL(xhr.response)
      const dom = document.createElement('a')
      dom.href = padLocalUrl
      dom.download = fileName
      if (navigator.msSaveBlob) {
        return navigator.msSaveBlob(xhr.response, fileName)
      }
      dom.click()
    }
  }
},


/**
 * 下载文件 用于excel导出
 * @param url
 * @param parameter
 * @returns {*}
 */
export function downFile(url, parameter) {
  return axios({
    url: url,
    params: parameter,
    method: 'get',
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded' //请求头 根据实际接口文档内容填写
    }
  })
}

/**
 * 下载文件
 * @param url 文件路径
 * @param fileName 文件名
 * @param parameter
 * @returns {*}
 */
export function downloadFile(url, parameter, fileName) {
  return downFile(url, parameter).then((data) => {
    if (!data || data.size === 0) {
      Vue.prototype['$message'].warning('文件下载失败')
      return
    }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx')
    } else {
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName + '.xlsx')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) //下载完成移除元素
      window.URL.revokeObjectURL(url) //释放掉blob对象
    }
  })
}

20.根据屏幕宽度自定改变菜单的长度

image.png

image.png

21.判断对象数组中是否存在相同的属性值

isRepeat (arr = [], key) {
  let hash = {}
  for (let i in arr) {
    if (hash[arr[i][key]]) {
      return true
    }
    hash[arr[i][key]] = true
  }
  return false
}

22.查找vue组件

/**
* vue找组件 向子/向父递归寻找符合名称的组件 cb函数参数接收
* @ compName :string  要找的组件的name属性
* @ vueCop   : object this/其他vue组件实例
* @ cb       :function 找到后以callbak函数的方式返回参数 需要定义接收
* 
*/
export function getChildVm4Name(vueCop, compName, cb) {
 if (Array.isArray(vueCop.$children) && vueCop.$children.length != 0) {
   for (let i = 0; i < vueCop.$children.length; i++) {
     if (vueCop.$children[i]['$options']['name'] == compName) {
       return cb(vueCop.$children[i])
     } else {
       getChildVm4Name(vueCop.$children[i], compName, cb)
     }
   }
 }
}

/**
* vue找组件 向子/向父递归寻找符合名称的组件 cb函数参数接收
* @ compName :string  要找的组件的_componentTag属性
* @ vueCop   : object this/其他vue组件实例
* @ cb       :function 找到后以callbak函数的方式返回参数 需要定义接收
* 
*/
export function getChildVm4Ctag(vueCop, compName, cb) {
 if (Array.isArray(vueCop.$children) && vueCop.$children.length != 0) {
   for (let i = 0; i < vueCop.$children.length; i++) {
     if (vueCop.$children[i]['$options']['_componentTag'] == compName) {
       return cb(vueCop.$children[i])
     } else {
       getChildVm4Name(vueCop.$children[i], compName, cb)
     }
   }
 }
}
/**
* vue找组件 线性 向子/向父递归寻找符合名称的组件 cb函数参数接收
* @ compName :string  要找的组件的name属性
* @ vueCop   : object this/其他vue组件实例
* void:VNode
* 
* 
*/
export function getParentVm4Name(vueCop, compName) {
 if(vueCop.$parent&&vueCop.$parent.$options){

   if(vueCop.$parent.$options.name == compName){
     return vueCop.$parent
   } else {
     return getParentVm4Name(vueCop.$parent,compName)
   }
 }
}

23.判断数组中是否存在

/**
* 如果值不存在就 push 进数组,反之不处理
* @param array 要操作的数据
* @param value 要添加的值
* @param key 可空,如果比较的是对象,可能存在地址不一样但值实际上是一样的情况,可以传此字段判断对象中唯一的字段,例如 id。不传则直接比较实际值
* @returns {boolean} 成功 push 返回 true,不处理返回 false
*/
export function pushIfNotExist(array, value, key) {
 for (let item of array) {
   if (key && item[key] === value[key]) {
     return false;
   } else if (item === value) {
     return false;
   }
 }
 array.push(value);
 return true;
}

24.前端读取xlsx

<p-upload
    name="file"
    accept=".xlsx"
    :show-upload-list="false"
    :customRequest="customRequest"
    >
    <p-button type="primary" size="small">
      导入数据
    </p-button>
 </p-upload>
import * as XLSX from 'xlsx/xlsx.mjs'

readFile(file){//文件读取
      return new Promise(resolve => {
        let reader = new FileReader();
        reader.readAsBinaryString(file);//以二进制的方式读取
        reader.onload = ev =>{
          resolve(ev.target.result);
        }
      })
    },
    async customRequest (info) {
      let file = info.file;
      if (!file){
        console.log('文件打开失败')
        return ;
      } else {
       let data = await this.readFile(file);
       let workbook = XLSX.read(data,{ type: 'binary'});//解析二进制格式数据
      //  console.log('二进制数据的解析:')
      //  console.log(workbook.SheetNames[0])
       let worksheet = workbook.Sheets[workbook.SheetNames[0]];//获取第一个Sheet
       let result = XLSX.utils.sheet_to_json(worksheet);//json数据格式
      //  console.log('最终解析的 json 格式数据:')
       console.log(result)
       result.forEach(element => {
         this.csotList.push({
            year: element['年份'],
            afwhole: element['xxx'],
            mfdWhole: element['xxx'],
            mdbWhole: element['xxx'],
            affactory: element['xxx-F'],
            mfdFactory: element['xxx'],
            mdbFactory: element['xxx'],
            afcash: element['xxx-F'],
            mfdCash: element['xxxxxx'],
            mdbCash: element['xxx'],
         })
       });
      }
    },

25.去除html标签

setTitle (title = '') {
  return title.replace(/<.*?>/g, '').replace(/[\r\n]/g, ' ').trim()
}