个人学习笔记(优化版)前端

213 阅读6分钟

1.接口请求状态值

100:临时响应

200:成功

300:重定向

400:访问错误

500:服务器错误;502无响应

2.css样式

隐藏滑动条:

ul::-webkit-scrollbar { display: none;}

控制placeholder:

:placeholder-shown

table设置tr标签无效:

border-collapse: collapse;

隐藏input密码框的小眼睛:

::-ms-reveal { display: none;}

input光标颜色:

input{caret-color:red;}

3.js

打印本页:

<el-button type="success" class @click="$print">

判断是否是元素节点:

node.nodeType==1;(1:元素节点,2:属性节点;3:文本节点)

判断类型:

Object.prototype.toString.call(参数)

获取自定义属性:

element.dataset / element.getAttribute

单行文本超出隐藏:

width: 500px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;

多行文本超出隐藏:

overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 4;

判断undefined:

typeof(exp) == 'undefined'

img中src动态拼接:

require(`../../assets/img/icon-${item.icon}.png`)

字符串转JSON对象 / JSON对象转字符串:

JSON.parse() / JSON.stringify()

label标签失效:

for对应id不唯一

检查自身属性中是否具有指定的属性:

Object.hasOwnProperty()

保留n位小数

Number(num).toFixed(n)

apply获取数组最大值最小值:

const arr = [15, 6, 12, 13, 16];
const max = Math.max.apply(Math, arr); // 16
const min = Math.min.apply(Math, arr); // 6

数组求和、最大值、最小值

//求和
array.reduce((a,b) => a+b);
//最大值
array.reduce((a,b) => a>b?a:b);
//最小值
array.reduce((a,b) => a<b?a:b);

去除重复值

const array  = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// Output: [5, 4, 7, 8, 9, 2]


判断对象是否具有指定的对象

Object.hasOwn(sert,'aaa')  //用来代替Object.prototype.hasOwnProperty

获取对象中的键值对数组

const obj = {name:"123",age:12};
console.log(Object.entries(obj))  // [["name","123"],["age","12"]]

对某些字符串实现前后填充,来实现某种格式化效果 padStart padEnd

//参数一填充的最大长度,参数二填充的字符。默认是空格填充。
const message = "Hello World"
const newMessage = message.padStart(15, "*").padEnd(20, "-")
console.log(newMessage) // ****Hello World-----
//如果填充的最大长度小于原字符串的长度,那么将会输出原字符串。
const message = "Hello World"
console.log(message.padStart(1, 0)) //Hello World
//如果用来补全的字符串与原字符串,两者的长度之和超过了最大长度,则会截去超出位数的补全字符串。
'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"

将嵌套的数组“拉平”,变成一维的数组。该方法返回一个新数组

//参数,表明需要展开多少层的数组。默认值为1。
[1, 2, [3, [4, 5]]].flat() // [1, 2, 3, [4, 5]]
[1, 2, [3, [4, 5]]].flat(2) // [1, 2, 3, 4, 5]
//如果不管有多少层嵌套,都要转成一维数组,可以用Infinity关键字作为参数。
[1, [2, [3]]].flat(Infinity) // [1, 2, 3]
//如果原数组有空位,flat()方法会跳过空位。
[1, 2, , 4, 5].flat() // [1, 2, 4, 5]

通过 Object.entries 将一个对象转换成 entries

const obj = {
  name: "zh",
  age: 22
}
const entries = Object.entries(obj)
const newObj = Object.fromEntries(entries)
console.log(newObj) //{ name: 'zh', age: 22 }

在es11之前,我们是通过||来运算的。但是它会存在一些问题。当前面一个运算数为0,""等时,依旧会赋值第二个运算数。

const foo = 0
const bar1 = foo || "default value"
const bar2 = foo ?? "defualt value"
console.log(bar1, bar2) // default value 0

将查询字符串转化成一个对象

const queryString = 'name=zh&age=2'
const queryParams = new URLSearchParams(queryString)
console.log(queryParams)  // {'name'=>'zh','age'=>'22'}
const paramObj = Object.fromEntries(queryParams)
console.log(paramObj);

4.jq

事件委托:

$("ul").on("click","li.box",function () {})

获取checkbox单选框是否被选中:

$("input name='reply']:checked").val()

5.vue2

强制重新渲染数据:

this.$forceUpdate()

设置高度无效:

html,body,#app {height: 100%;}

在子组件中写点击事件:

@click.native="click()"

vue父组件调用子组件的form的rule验证:

this.$refs["SelectTime"].$refs.ruleForm.validate(async (valid) => {  })

props父传子:

props:{ title:{ type:Object,default:()=>{ return '123' } } }

watch深度监听:

firstName:{handler:function(newVal,oldVal){},deep:true}

获取元素高度:

this.$refs.slideBox[0].offsetHeight

通过自定义属性实现节流:

    <button v-debounce>确定</button>

    import Vue from "vue";

    Vue.directive("debounce", {

      //节流实现

      inserted: function(el, binding) {

        el.addEventListener("click", () => {

          if (!el.disabled) {

            el.disabled = true;

            setTimeout(() => {

              el.disabled = false;

            }, binding.value || 3000);

          }

        });

      }

    });

6.vue3

获取ref:

const MyHome = ref<HTMLElement|null>(null)

引用第三方组件库:

declare global { interface Window {  vrv: any; }} 
或者 
declare var vrv: any;=>(shims-vue.d.ts)
[.eslintrc.js]中globals:{vrv:true};

向ESLint规则中添加全局变量:

.eslintrc.js中globals

父传子/props获取传值错误:

list: {type: Array,default:null,},

子组件传值到父组件:

context.emit("children",'123'); 
还需要定义
emitsemits: ["children"],

动态渲染url图片无效:

url: require("../../assets/img/exam/img-1.png"),

使用vuex

import { useStore } from "vuex";
let store = useStore();
store.state.annualCheck.otherData
使用mutations的方法
store.commit("annualCheck/examTimeChange", number);
使用actions的方法
store.dispatch("user/setuser", userObj);

7.typescript

事件获取传参对象

function text(item: { objType: string; id: string; }){   }

8.正则表达式

获取富文本中的图片地址并进行替换../

str = str.replace(/src="(\.\.\/)*(\w+\/)+\w+\.(bmp|jpg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|jpeg)/gi,v=>{
  v = v.replace(/\.\.\//,'10.0.0.72:8080/common')
  return v;
})

9.Vs code

Format On Save 保存后自动格式化

10.SourceTree

开启文件大小写识别:设置--编辑配置文件:ignorecase = true【false:开启大小写】

11.Element-ui

//验证
this.$refs.examine.validateField("barCode");
this.rules.barCode= [{ required: true, message: '请上传图片' }]
//取消验证
this.$refs.examine.clearValidate('barCode');

//input只允许输入数字
 @change="value=value.replace(/[^\d]/g,'')"

12.uni-app

返回上一页并刷新

let pages = getCurrentPages(); // 当前页面
let beforePage = pages[pages.length - 2]; // 上一页
uni.navigateBack({
    success: function() {
        beforePage.onLoad(); // 执行上一页的onLoad方法,不生效通过输出beforePage,查找操作
        
    }
});

获取状态栏高度

手机的配置信息
uni.getSystemInfoSync()
导航栏高度
uni.getSystemInfoSync().statusBarHeight

13.英文

handle //操作
self //自己
secretary //书记
check //考核
increased //新增
decrease //减少
edit //编辑
push //推送
Apush //已推送
issue //发布
Aissue //已发布
totalPoints //总分
decide //判断

14.eCharts

xAxis:
  name //坐标轴名称
  boundaryGap //坐标轴两边留白策略
  axisTick:{
    show:false, //是否显示坐标轴刻度(小尖尖)
  }
  axisLable:{
    align:"center", //坐标轴下文字对齐方式
    fontSize:10, //文字大小
    interval:0, //显示数据时的间隔数
  }
yAxis:
  splitNumber:5, //坐标轴的分割段数
  offset:-20, //y轴相对于默认位置的偏移
  min:0, //坐标轴刻度最小值
  max:100, //坐标轴刻度最大值
  [axisLable] //同xAxis
grid:
  left:0, //canvas组件距离左侧绝对值
  top:10%, //canvas组件距离顶部百分比
  right:10,
  bottom:60,

series:
  avoidLabelOverlap:false, //是否启用防止标签重叠
  label:{
    show:true,
    posittion:"center",
    fontSize:18,
    fontWeight:"bold",
    padding:[-100,0,0,0],
    /*
      {a}:系列名
      {b}:数据名
      {c}:数据值
      {d}:百分比
      {@xxx}:数据中名为 'xxx' 的维度的值,如 {@product} 表示名为 'product' 的维度的值
      {@[n]}:数据中维度 n 的值,如 {@[3]} 表示维度 3 的值,从 0 开始计数
    */
    formatter: '{b}: {d}', //支持字符串模板和回调函数两种形式:formatter:()=>{return '123'}
    color:"#ff3241",
  },
  itemStyle:{
    borderRadius:[15,15,0,0],//(顺时针左上,右上,右下,左下)
    //渐变色效果,如果使用第一种方式存在鼠标放上颜色变淡,可以使用第二种方式,改为相同颜色
    //第一种方式,一种颜色
    color:"#ff3241",
    //第二种方式,渐变色
    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      {offset: 0,color: "#fe9516"},{offset: 1, color: "#ffcb8c"},
    ]),
  },
  symbol:"base64", //标记的图形
  symbolSize: 18, //标记的大小
  symbolRotate: 6, //标记的旋转角度
  barWidth: 57, //柱状图柱子宽度

15.面试题

i18n:Vue I18n 是 Vue.js 的国际化插件。实现中英文切换

call,apply,bind的区别

作用:call、apply、bind作用是改变函数执行时的上下文,改变this指向
区别:
  apply:
    接受两个参数,第一个参数是this的指向,第二个参数是函数接受的参数,以数组的形式传入
    改变this指向后原函数会立即执行,且此方法只是临时改变this指向一次
    当第一个参数为null、undefined的时候,默认指向window(在浏览器中)
  call:
    接受n个参数,第一个参数是this的指向,第二个以及第二个往后都是参数
    改变this指向后原函数会立即执行,且此方法只是临时改变this指向一次
    当第一个参数为null、undefined的时候,默认指向window(在浏览器中)
  bind:
    bind方法和call很相似,第一参数也是this的指向,后面传入的也是一个参数列表(但是这个参数列表可以分多次传入)
    改变this指向后不会立即执行,而是返回一个永久改变this指向的函数

实现bind

Function.prototype.myBind = function (context) {
    // 判断调用对象是否为函数
    if (typeof this !== "function") {
        throw new TypeError("Error");
    }
    // 获取参数
    const args = [...arguments].slice(1),
          fn = this;
    return function Fn() {
        // 根据调用方式,传入不同绑定值
        return fn.apply(this instanceof Fn ? new fn(...arguments) : context, args.concat(...arguments)); 
    }
}

16.npm

安装yarn

npm install -g yarn
##检查是否安装成功
yarn --version
##yarn换源 安装淘宝镜像
yarn config set registry https://registry.npm.taobao.org
##yarn全局安装vite
yarn create vite@2.7.2