前端开发总结的一些技巧和实用方法

129 阅读3分钟

1.快速从url获取参数

let code = new URL(location.href).searchParams.get('code')

2.滚动触底分页

mounted(){
    window.addEventListener('scroll', this.handleScroll) // 监听页面滚动
},
methods:{
    handleScroll() {
        let _this = this;
        let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
        let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
        this.scrollTop = scrollTop;
        //触底分页
        if(scrollTop + windowHeight >= scrollHeight-20 && !this.threadForm.more){
          console.log("分页");
          this.getThreadList();
        }
}

3.组装扁平化数组

function arrayToTree(items) {
  const result = [];   // 存放结果集
  const itemMap = {};  // 
  for (const item of items) {
    const id = item.id;
    const pid = item.pid;

    if (!itemMap[id]) {
      itemMap[id] = {
        children: [],
      }
    }

    itemMap[id] = {
      ...item,
      children: itemMap[id]['children']
    }

    const treeItem =  itemMap[id];

    if (pid === 0) {
      result.push(treeItem);
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = {
          children: [],
        }
      }
      itemMap[pid].children.push(treeItem)
    }

  }
  return result;
}

4.合并数据

const a = [1,2,3];
const b = [1,5,6];
const c = [...new Set([...a,...b])];//[1,2,3,5,6]

const obj1 = {
  a:1,
}
const obj2 = {
  b:1,
}
const obj = {...obj1,...obj2};//{a:1,b:1}

5.简化if判断条件

//不好的方法
if(type == 1 || type == 2 || type == 3 ||type ==4 ||{}
//建议的方法
const condition = [1,2,3,4];
if( condition.includes(type) ){
   //...
}
//字符串是否包含另一个字符串
let str = "I Love javascript"
str.includes("javaScript");

6.前端列表模糊搜索

//模糊搜索
setValue: Debounce(function (e) {
    this.newSearch();
}),
newSearch() {
    this.searchData.data = this.tableData.data.filter((item) => item.pro_name.indexOf(this.searchKeyword) > -1);
},

7.输入框非空的判断

//错误方式
if(value !== null && value !== undefined && value !== '')
//建议方式
if((value??'') !== '')

8.深克隆

//深克隆
deepClone(obj) {
    let newObj = Array.isArray(obj) ? [] : {}
    if (obj && typeof obj === "object") {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          newObj[key] = (obj && typeof obj[key] === 'object') ? this.deepClone(obj[key]) : obj[key];
        }
      }
    }
    return newObj
},

9.字符串查找替换

let imgStr = [
    '<img src="https://aliyuncs.com/348.jpg" alt="">',
    '<img src="https://aliyuncs.com/348.jpg" alt="">',
    '<img src="https://aliyuncs.com/348.jpg" alt="">',
];
let str = imgStr.join(',').replace(/,/g,'');

10 轮训定时器

createSetInterval(order_id) {
    this.stopSetInterval();
    //this.timer = '';
    this.timer = setInterval(() => {
        this.getOrderResult(order_id);
    }, 2000);
},
stopSetInterval() {
    if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
    }
},
getOrderResult(id){
    //接口响应成功以后销毁定时器
    this.stopSetInterval();
}

11 数组 map 的方法 (不使用Array.Map)

Array.from 还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。如下:

const cities = [    
    { name: 'Paris', visited: 'no' },    
    { name: 'Lyon', visited: 'no' },    
    { name: 'Marseille', visited: 'yes' },    
    { name: 'Rome', visited: 'yes' },    
    { name: 'Milan', visited: 'no' },    
    { name: 'Palermo', visited: 'yes' },    
    { name: 'Genoa', visited: 'yes' },    
    { name: 'Berlin', visited: 'no' },    
    { name: 'Hamburg', visited: 'yes' },    
    { name: 'New York', visited: 'yes' }
];

const cityNames = Array.from(cities, ({ name}) => name);
console.log(cityNames);
//["Paris", "Lyon", "Marseille", "Rome", "Milan", "Palermo", "Genoa", "Berlin", "Hamburg", "New York"]

12 有条件的对象属性

不再需要根据一个条件创建两个不同的对象,可以使用展开运算符号来处理。

let getUser = (emailIncluded) => {
  return {
    name: 'John',
    surname: 'Doe',
    ...emailIncluded && { email : 'john@doe.com' }
  }
}

const user = getUser(true);
console.log(user); // outputs { name: "John", surname: "Doe", email: "john@doe.com" }

const userWithoutEmail = getUser(false);
console.log(userWithoutEmail); // outputs { name: "John", surname: "Doe" }

13. 动态属性名

const dynamic = 'email';
let user = {
    name: 'John',
    [dynamic]: 'john@doe.com'
}
console.log(user); // outputs { name: "John", email: "john@doe.com" }

14.函数默认参数妙用

场景:假设我们又如下的初始化工作需要进行,在代码的最开始我们需要对config对象进行初始化工作

unction initConfig(config) {
    config.map((item) => {
        item.content = Number(item.content)
    })
}

如果我们不小心忘记给它传递参数,浏览器会报如下错误,提示我们 config 没有 map 方法,因为此时 config 为 undefined

解决办法:

我们可以给函数的参数加上一个默认的值

function initConfig(config = []) {
    config.map((item) => {
        item.content = Number(item.content)
    })
}

15.监听DOM元素是否在可是区域内

场景:如果打开网页,DOM元素在可视区域内,就不展示一个div,反之如果需要滑动网页才能让这个DOM元素出现在可视区域,就展示这个div。这里分享一个vue的做法。

mounted(){
let recommend = document.getElementById('replyList'),that = this;
	let observer = new IntersectionObserver(function(entries){
		entries.forEach( function(element, index) {
			if (element.isIntersecting ) {
			//用recommendShow这个布尔值来控制DOM是否显示
				that.recommendShow = false;
			} else {
				that.recommendShow = true;
			}
		});

	}, {
		root: null,
		threshold:[0, 1]
	});

	observer.observe(recommend)
}

16.谷歌浏览器A标签跳转新标签导致sessionStorage无效

解决方法:主动添加 rel="opener" 属性即可,如下。

<a href="#" rel="opener" target="_blank">跳转</a>

17.Array.find

如果你曾经编写过普通 JavaScript 中的 find 函数,那么你可能使用了 for 循环。在 ES6 中,介绍了一种名为 find()的新数组函数,可以实现 for 循环的简写。

const pets = [
  { type: 'Dog', name: 'Max'},
  { type: 'Cat', name: 'Karl'},
  { type: 'Dog', name: 'Tommy'},
]
function findDog(name) {
  for(let i = 0; i<pets.length; ++i) {
    if(pets[i].type === 'Dog' && pets[i].name === name) {
      return pets[i];
    }
  }
}

简写为

let = pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

18.数组提取不重复的新值

如果有下面两个数组,需要提取第二个中与第一个数组中不重复的新值,也就是单独把5,6提取出来

let arr1 = [1,2,3];
let arr2 = [2,5,6];
let arr3 = [];
arr2.forEach(item=>{
    if(!arr1.includes(item)){
        arr3.push(item);
    }
})
console.log(arr3);//[5,6]

19 绕过git hook提交

git commit --no-verify -m "commit message"