全部
常见问题
产品动态
精选推荐

前端开发中的一些技巧和实用方法(1)

管理 管理 编辑 删除

e68f4202302141421166803.jpeg

1.快速从url获取参数

//http://www.xxxx.com?code=123&id=1
let code = new URL(location.href).searchParams.get('code')

2.滚动触底分页加载数据

data(){
    return {
        loading: false,
        page:1,
        limit:10,
        threadList:[]
    }
},
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();
    },
    getThreadList(){
        if(this.loading) return
        this.loading = true;
        fetch(`/api/getList?page=${this.page}&limit=&{this.limit}`).then(response => response.json()).then(data => {
            this.loading = false;
            var list = data.data;
            var showStatus = list.length < this.limit;
			//接口返回数量小于分页条数为true
            this.page++;
            this.threadList = this.threadList.concat(list);
            this.page = this.page;
        })
    }
}

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.searchKeyword为输入框的关键词,用列表的数据去匹配输入框的关键词进行筛选
    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.轮训定时器

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){
    //接口响应成功以后销毁定时器
    fetch('/api/xxx').then(response => response.json()).then(data => {
          if (data.status == 200) {
              this.stopSetInterval();
         }
    })
}

10.对象验证方式

如果我们有一个这样的对象:

const parent = {
    child: {
      child1: {
        child2: {
          key: 10
      }
    }
  }
}

很多时候我们会这样去写,避免某一层级不存在导致报错:

parent && parent.child && parent.child.child1 && parent.child.child1.child2

这样代码看起来就会很臃肿,可以使用JavaScript的可选链运算符:

parent?.child?.child1?.child2

这样实现和效果和上面的一大长串是一样的。​

可选链运算符同样适用于数组:

const array = [1, 2, 3];
array?.[5]

可选链运算符允许我们读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。在引用为空(null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined。

请登录后查看

徐斗明 最后编辑于2023-11-16 18:01:22

快捷回复
回复({{post_count}}) {{!is_user ? '我的回复' :'全部回复'}}
回复从新到旧

{{item.user_info.nickname ? item.user_info.nickname : item.user_name}}

作者 管理员 企业

{{item.floor}}# 同步到gitee 已同步到gitee {{item.is_suggest==1? '取消推荐': '推荐'}}
{{item.floor}}#
{{item.user_info.title}}
附件

{{itemf.name}}

{{item.created_at}}  {{item.ip_address}}
{{item.like_count}}
{{item.showReply ? '取消回复' : '回复'}}
删除
回复
回复

{{itemc.user_info.nickname}}

{{itemc.user_name}}

作者 管理员 企业

回复 {{itemc.comment_user_info.nickname}}

附件

{{itemf.name}}

{{itemc.created_at}}   {{itemc.ip_address}}
{{itemc.like_count}}
{{itemc.showReply ? '取消回复' : '回复'}}
删除
回复
回复
查看更多
回复
回复
1897
{{like_count}}
{{collect_count}}
添加回复 ({{post_count}})

相关推荐

乡关何处 作者
学会提问:说明自己有哪些操作,什么情况下出现的具体问题表现,尝试了什么解决方案。尽可能截图说明,请勿只问什么什么不行怎么办~。昵称后面的二维码可以添加到我的企业微信,请备注好问题

回答

708

发布

45

经验

11243

快速安全登录

使用微信扫码登录
{{item.label}} {{item.label}} {{item.label}} 板块推荐 常见问题 产品动态 精选推荐 首页头条 首页动态 首页推荐
加精
取 消 确 定
回复
回复
问题:
问题自动获取的帖子内容,不准确时需要手动修改. [获取答案]
答案:
提交
bug 需求 取 消 确 定

微信登录/注册

切换手机号登录

{{ bind_phone ? '绑定手机' : '手机登录'}}

{{codeText}}
切换微信登录/注册
暂不绑定
CRMEB客服

CRMEB咨询热线 咨询热线

400-8888-794

微信扫码咨询

CRMEB开源商城下载 开源下载 CRMEB官方论坛 帮助文档
返回顶部 返回顶部
CRMEB客服