日常开发遇到的一些方法

日常开发遇到的一些方法

1.数组方法find查找

let arr=[1,2,3,4,5,6]
let a=arr.find(item=>item>3)
console.log(a)//4
-----------------------------------
let b=arr.find(item=>item==2)
console.log(b)//4
-----------------------------------
let arr2=[
            {name:"12",age:18},
            {name:"13",age:17},
            {name:"14",age:11}
        ]
let c=arr.find(item=>item.name=="12")
console.log(c)//{name:"12",age:18}

2.every()和some()的用法

every()是对数组中每一项运行给定函数,如果该函数对每一项返回true,则返回true。
some()是对数组中每一项运行给定函数,如果该函数对任一项返回true,则返回true。
1.every()所有的都是对着返回true
2.some()有一个对的返回true

var arr = [ 1, 2, 3, 4, 5, 6 ]; 

console.log( arr.some( function( item, index, array ){ 
    console.log( 'item=' + item + ',index='+index+',array='+array ); 
    return item > 3; 
})); 
//true
console.log( arr.every( function( item, index, array ){ 
    console.log( 'item=' + item + ',index='+index+',array='+array ); 
    return item > 3; 
}));
//false
----------------------------------------------
if(resArr.every(item=>item=="")){
          return true
        }else{
          return false
        }

3.Json转化

1.字符串转对象

JSON.parse
----------------------------------------------
 res.data.goods = [JSON.parse(res.data.goods_info)].map(item => {
          return {
            ...item,
            main_image_url: res.data.main_image_url,
          };
        });

2.对象转字符创

JSON.stringify()
------------------------------------------
var j={"name":"binchen"};
JSON.stringify(j)

4.修改input的焦点问题(css)

取消默认样式

outline:none;

使用:focus的伪类元素进行设置

5.!important

最高优先级

6.文件后缀名截取

<! 不要点---->
name.substring(name.lastIndexOf(".")+1)
<! 要点---->
row.substring(row.lastIndexOf("."))
--------------------------------------
lastIndexOf(".") //字符串从后向前搜索选择的字符
substring(".") //从所选的的地方像后截取
split(" ")//以空格字符串转成数组

7.字符串转数组

1、split() 方法

const text = "abc";
const chars = text.split('');
console.log(chars);
//['a', 'b', 'c']

2、展开运算符

const text = "abc????";
const chars = [ ...text ];
console.log(chars);
//["a", "b", "c", "????"]

3、解构赋值

const text = "abc????";
const [ ...chars ] = text;
console.log(chars);
//["a", "b", "c", "????"]

4、Array.from

const text = "abc????";
const chars = Array.from(text);
console.log(chars);
//["a", "b", "c", "????"]

8.数组转字符串方法

1. toString()

var a = [1,2,3,4,5,6,7,8,9,0];  //定义数组
var s = a.toString();  //把数组转换为字符串
console.log(s);  //返回字符串“1,2,3,4,5,6,7,8,9,0”
console.log(typeof s);  //返回字符串string,说明是字符串类型

2.join()

var a = [1,2,3,4,5];  //定义数组
var s = a.join("==");  //指定分隔符
console.log(s);  //返回字符串“1==2==3==4==5”

9.动态行内样式

:style="{width: descriptionWidth }"

10.取消光标的方法

caret-color: transparent;

11.vue阻止冒泡事件

@click.native.stop

12.动态添加健的方法

let key=......
Object[key]

13.VUE中正则校验(车牌号)

 let carNumberPlate=(rules, value, callback)=>{
      var iscode=/^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(value)
     if(!iscode){
        callback(new Error("请输入正确的车牌号"))
      } else{
        callback()
      }
    }
    ------------------------------------------
     carNumberPlate: [
          { required: true,  validator: carNumberPlate, trigger: "blur" },
        ],

14.$set 添加对象的属性

给data对象新增属性,并触发视图更新

mounted () {
    this.$set(this.student,"age", 24)
}

15.$delete 删除对象的属性

this.$delete(row,prop)

15.foreach流程异常停止

let arr = [1, 2, 3]
try {
	arr.forEach(item => {
		if (item === 2) {
			throw('循环终止')
		}
		console.log(item)
	})
} catch(e) {
	console.log('e: ', e)
}

16.vue下载文件时的封装方法

export function downFile(url, parameter) {
  return axios({
    url:process.env.VUE_APP_BASE_API+ url,
    params: parameter,
    method: "get",
    responseType: "blob",
  });
}
/**  * 下载文件  * @param url 文件路径  * @param fileName 文件名  * @param parameter  * @returns {*}  */
export function downloadFile(url, fileName, parameter) {
  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]), fileName);
    } 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);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }
  });
}

17. vue手动更新视图层

      this.$forceUpdate()

18 .Vue传值——bus总线机制

在utils文件夹下面定义一个bus.js,这样一个中央事件总线就定好了,里面内容就这两行:

import Vue from 'vue'
export const Event = new Vue() // 定义一个事件总线

传递方:

import { Event } from '../../utils/bus'  // 引入这个事件总线
export default {
  data() {
    userId: ''
  }
  watch: {
    userId() {  // 监听userId改变时触发事件,当然你可以在所有其他事件去触发$emit
      Event.$emit('changeUser', userId) // $emit接收参数,一个是触发的事件名,一个是携带的参数
    }
}

接收方:

import { Event } from '../../utils/bus' // 依然是把bus总线引进来
export default {
created() {
    Event.$on('changeSonRoute',showIndex => {  // $on接收发送方传给我们的数据
      console.log(showIndex)
    })
  }
}

19.防抖和节流与闭包的关系

1.防抖

让事件在触发后N秒后执行,如果在N秒内重新触发,则重新计算时间

应用场景

1.按钮双击,我们平时电脑上快速双击就有可能触发两次点击事件
2.输入框的input或者change时间
3.轮动条
立即执行版
立即执行版防抖与节流类似
```js
    // 简单版防抖函数,添加立即执行,当immediate为true的时候执行
function debounce(func, time = 2000, immediate = true) {
    let timer = null;
    return function () {
        if (!timer) { // 如果再次触发则清空.
            timer = setTimeout(() => {
                !immediate && func();
                timer = null;
            }, time)
            immediate && func()
        }
    }
}

```
非立即执行版
主要原理就是再次触发方法的时候把上次的计时器清除掉
```js
    // 简单版,实现了防抖的功能,无法传参
// 其实防抖和节流都是闭包 后面再讨论
function debounce(func, time = 2000) {
    // 第一次执行 timer =null
    let timer = null;
    // 这里为什么声明一个timer?  因为debounce返回了一个函数,而函数内部访问了timer这个变量,这样会导致timer不会被回收
    // 这也是使得第二次执行的时候为什么timer不会再次为null
    return function () {
        // 第一次执行肯定为null所以进入
        if (!timer) { 
            // timer此时不为空了
            timer = setTimeout(() => {
                func(); // 执行外部传来的函数
                timer = null; // 再次把timer设为null 使得函数可以再次执行
            }, time)
        }
    }
}

```
最终版防抖函数
    // 最终版,实现了防抖的功能,无法传参
    // 其实防抖和节流都是闭包 后面再讨论
    function debounce(func, time = 2000) {
        // 第一次执行 timer =null
        let timer = null;
        // 这里为什么声明一个timer?  因为debounce返回了一个函数,而函数内部访问了timer这个变量,这样会导致timer不会被回收
        // 这也是使得第二次执行的时候为什么timer不会再次为null
        return function (...args) { // 传参
            // 第一次执行肯定为null所以进入
            if (!timer) {
                // timer此时不为空了
                timer = setTimeout(() => {
                    func.apply(this, args) // 执行外部传来的函数
                    timer = null; // 再次把timer设为null 使得函数可以再次执行
                }, time)
            }
        }
    }

节流

在规范时间内,只能触发一次函数,如果多次触发不会执行
```js
    // 简单版,节流其实就比防抖多了一步
function throttle(func, time) {
    let timer = null;
    return function (...args) {
        if (timer) {// 第二次触发的时候,
            //节流:如果还在规定的时间内,则什么也不执行
            //防抖: 重新计时
            return;
        }
        timer = setInterval(() => {
            timeout = null;
            func.apply(this, args)
        }, time)
    }
}

```

20.返回页面后数据不跟新 (路由守卫解决,进入路由时的钩子函数beforeRouteEnter)

 beforeRouteEnter(to,from,next){
    next((e)=>{
      e.getMyTaskList()
    })
  },

21.截取数组对象里面的一项并删除

1.findIndex

条件选择返回选择的哪一项的下标

2.splice

1. 删除功能,第一个参数为第一项位置,第二个参数为要删除几个
2. 2. 插入功能,第一个参数(插入位置),第二个参数(0),第三个参数(插入的项)。用法:array.splice(index,0,insertValue),返回值为空数组,array值为最终结果值。
3.替换功能,第一个参数(起始位置),第二个参数(删除的项数),第三个参数(插入任意数量的项)。用法:array.splice(index,num,insertValue),返回值为删除内容,array为结果值
let fileIndex = this.tableData.findIndex((item) => item == row); this.tableData.splice(fileIndex, 1);

23.查询是否数组中是否存在,并返回下标 indexOf

   if (targetARR.indexOf(3) != -1
不存在就返回-1

24,返回对象的key,放到数组中,可以遍历出来 Object.keys

  const objArr = Object.keys(this.projectTargetScore);
  ------------------------------------------------------------
  //可以遍历健 查询值
      objArr.forEach((item) => {
       
      });

25.vue路由跳转时用parmas跳转时 保存数据状态

跳转时需要在路由配置一下 ,并使用name跳转

router下面的代码

{
  
    path: '/todo',
    component: Layout,
    hidden: true,
    redirect: 'noredirect',
    children: [
      {
        path: 'businessHandling/:processInstanceId/:taskId/:processCategory/:businessKey/:version',
        <!需要的参数要拼到path后面---->
        component: () => import('@/views/comprehensive/todo/businessHandling.vue'),
        name: 'BusinessHandling',
        meta: {
          title: '流程办理',
          activeMenu: '/comprehensive/todo'
        }
      }
    ]
  }

使用跳转时:

this.$router.push({
        name: 'BusinessHandling',
        <!这种情况下不能用path跳转,要使用name---->
        params: {
          processInstanceId: row.processInstanceId,
          taskId: row.taskId,
          processCategory: row.processCategory,
          businessKey: row.businessKey,
          version:row.version
          
        }
      })

26.取消焦点

outline:none;

27.el-table 单元格样式

:row-style="{height:'40px'}"
:cell-style="{padding:'0px'}"

28.获取url

   console.log(window.location.href, 999)
            let url = window.location.href
            let p = url.split('?')[1]
            let params = new URLSearchParams(p)
            console.log(params,444)
            console.log(params.get('businessId')) //1
            console.log(params.get('permission')) //1
            console.log(params.get('dataSource')) //1
            console.log(params.get('projectName')) //1

29.delete 用法

只能用来删除对象

var o = { x: 1 };
delete o.x; // true
o.x; // undefined

30.背景虚化

#carouselChart {
    width: 100%;
    height: 700px;
position: relative;
}

#carouselChart::before {
    background: url(../img/01.jpg) no-repeat;
    background-size:100% 100%;
    width: 100%;
    height:700px;
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
    /*-1 可以当背景*/
    -webkit-filter: blur(3px);
    filter: blur(3px);
}

31.js事件执行顺序

同步任务/非耗时任务:指的是在主线程上排队执行的任务,只有前一个执行完毕才能执行后一个任务。

异步任务/耗时任务:由js委托给宿主环境进行执行,执行完后会通知js主线程执行异步任务的回调函数。

异步任务又分为宏任务和微任务

js的事件执行顺序是这样的:

宏任务:异步ajax请求、setTimeout、setInterval、文件操作、其他
微任务:Promise.then、.catch 和.finally,process.nextTick、其他

执行顺序查看有没有微任务,有微任务,先执行所有的微任务,在去执行下一个宏任务,执行结束完所有的宏任务就执行完毕

js是单线程的,从上到下执行:

从上到下执行,同步任务执行,异步任务扔到任务队列里等待。所有同步任务(执⾏栈中执行)执行完,去到任务队列里
从上到下执行宏任务,new promise实例的时候是同步任务,所以promise里的语句立即执行,.then()里面的语句是微任务,放到微任务队列。每当有一个宏任务执行完毕就检查是否有微任务,有就把微任务先执行。一直这样循环。
js是单线程的,是从上往下执行,执行时js任务分为两种同步任务(非好时任务,可以马上执行完的任务)和异步任(耗时性任务),其中异步任务被分为宏任务(异步ajax请求、setTimeout、setInterval、文件操作、其他)和微任务(Promise.then、.catch 和.finally,process.nextTick、其他)
那么执行顺序是
1.先从上往下执行同步任务,吧所有的异步放到任务队列里,
2.同步任务执行完
3.任务队列里从上往下查看有没有微任务,有微任务执行微任务
4.没有执行执行任务队列里的宏任务
5.安以上顺序执行完之后(宏任务里面1,2,3)
6.到下一个宏任务

32.nextTick的作用

 1.nextTick 就是设置一个回调,用于异步执行。
2.就是把你设置的回调放在 setTimeout 中执行,这样就算异步了,等待当时同步代码执行完毕再执行。
3.当页面上的元素被重新渲染之后,才会执行指定回调函数中的代码。
```js
this.$nextTick(_ => {
    this.$refs.saveTagInput.$refs.input.focus();
  });

```
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值