前端代码优化(持续更新中)
优化
1、if语句优化
1、初学
returnWeekday() {let string = '今天是星期'const date = new Date().getDay()if (date === 0) {string += '日'} else if (date === 1) {string += '一'} else if (date === 2) {string += '二'} else if (date === 3) {string += '三'} else if (date === 4) {string += '四'} else if (date === 5) {string += '五'} else if (date === 6) {string += '六'}return string
}
2、入门
- switch替代
returnWeekday() {let string = '今天是星期'const date = new Date().getDay()switch (date) {case 0 :string += '日'breakcase 1 :string += '一'breakcase 2 :string += '二'breakcase 3 :string += '三'breakcase 4 :string += '四'breakcase 5 :string += '五'breakcase 6 :string += '六'break}return string
}
3、中级
- 数组替代
returnWeekday() {const string = '今天是星期'const date = new Date().getDay()const dateArr = ['天', '一', '二', '三', '四', '五', '六']return string + dateArr[date]
}
- 对象替代
returnWeekday() {const string = '今天是星期'const date = new Date().getDay()const dateObj = {0: '天',1: '一',2: '二',3: '三',4: '四',5: '五',6: '六'}return string + dateObj[date]
}
4、其他常见优化
1、三元表达式
const offsetTop = 1
if( offsetTop < 0 ){this.titleFixed = true
} else {this.titleFixed = false
}// 改成三元
(offsetTop < 0) ? this.titleFixed = true : this.titleFixed = false
2、逻辑运算符:&&
const flag = true
if( flag ){methods()
}// 与运算符
flag && methods()
3、includes
const code = '202'
if( code === '202' || code === '203' || code === '204' ){methods()
}
// includes
if( ['202','203','204'].includes(code) ){methods()
}
// 进一步
(['202','203','204'].includes(code)) && methods()
2、过滤器优化
//oldVue.filter('converterPlatform', value => {if (value === 'FEIZHU_WEELFLYPLANET') {return '飞猪'} else if (value === 'TONGCHENG') {return '同程艺龙 '} else if (value === 'MEITUAN') {return '美团'} else if (value === 'ALL') {return 'ALL'}
})// new
import store from './store'
const { getters: { platform, orderStatusList } = {} } = store
// 平台
Vue.filter('converterPlatform', value => {for (let i = 0; i < platform.length; i++) {if (value === platform[i].platformId) return platform[i].platformName}
})
3、操作优化
// 处理更多菜单内容
handleCommand(command) {switch (command) {case 'groupingManageVisible':case 'groupingAddPictureVisible':case 'tagsManageVisible':this[command] = truebreakdefault:this.handleCheckIsEmpty() && (this.hotelIds = this.multipleSelection.join(','), this.handleMoreOperation(command))break}
}
// 处理必须选中一行操作项
handleMoreOperation(command) {switch (command) {case 'batchSoldOut':case 'batchPutaway':this.hotelStandUpDownVisible = truethis.hotelTitle = commandbreakcase 'joinTags':case 'outTags':this.joinTagsVisible = truethis.operatingState = commandbreakcase 'batchChangeSchemeVisible':case 'batchJoinGroupVisible':this[command] = truebreakcase 'batchOutGroup':this.assignGroup(this.hotelIds, '')breakdefault:break}
}// old
// 锁单
handleOrderLock({ orderId }) {this.orderId = orderIdthis.lock()
},
// 确认有房
handleConfirmHaveRoom({ orderId }) {this.orderId = orderIdthis.confirm()
},
// 拒单
handleRefusedOrder({ orderId }) {this.orderId = orderIdthis.deny()
},
handleConfirmQunarHaveRoom({ orderId }) {// 去哪儿游贝、嗨飞情况填写确认信息this.orderId = orderIdthis.qunarArrangeRoomVisible = true
},
// 查看酒店信息
handleViewHotelInfo({ hotelId }) {this.hotelIds = hotelIdthis.viewHotelInfoVisible = true
},// new
// 处理操作请求
handleOperation({ orderId }, type) {this.orderId = orderIdthis[type]()
},
// 处理组件显示
handleComponentVisible({ hotelId, orderId }, type) {this.hotelIds = hotelIdthis.orderId = orderIdtype === 'joinTagsVisible' && (this.operatingState = 'joinTags')this[type] = true
},
// old
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2ylAqZ27-1627955064945)(/Users/wangpeng/Desktop/optimize/子组件绑定方法.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1jZYpCvZ-1627955064948)(/Users/wangpeng/Desktop/optimize/组件展示隐藏方法.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0mgDwbo2-1627955064949)(/Users/wangpeng/Desktop/optimize/子组件调用父组件方法.png)]
// new
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ufQHe29c-1627955064951)(/Users/wangpeng/Desktop/optimize/优化后子组件方法.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-n35eRMX9-1627955064952)(/Users/wangpeng/Desktop/optimize/优化后子组件调用父组件方法.png)]
3、ES6
1、const与let变量
- 优化var 声明带来的全局污染
- const、let值在代码块中生效{}
- const 声明的变量必须赋值初始化,同一作用域不可重新声明或重新赋值
- let 声明的变量可以重新赋值,同意作用域不可重新声明
2、模板字面量
- 拼接字符串,
倒引号
表示,${}
占位符
// ES6之前 + 或者concat()
let taggingStr = ''
taggingArr.forEach(item => {taggingStr += '<dd value="' + item.tagValue + '"><a>' + item.tagName + '</a></dd>'
})//ES6
let taggingStr = ''
taggingArr.forEach(item => {taggingStr += `<dd value="${item.tagValue}"><a>${item.tagName}</a></dd>`
})
3、解构
使用解构从数组和对象提取值并赋值给独特的变量
// 数组
const point = [10, 25, -34]
const [x, y, z] = point
// 将数组中的值存储在其中的变量
console.info(x, y, z) //10 25 -34// 对象
const layui = {element: 1,table: 2,commonUtils: 3
}
const { element, table, commonUtils } = layui
// 将对象中的属性存储到其中的变量
console.info(element, table, commonUtils) // 1 2 3
4、对象字面量简写
// old
selectPayChannelv2({ productId, channel, platformPayPrice, extOrderInfo, platformPrice, hotelId, roomId, checkIn, checkOut, supplierId }) {this.PayChannelv2Data.orderId = this.$route.query.orderIdthis.PayChannelv2Data.productId = productIdthis.PayChannelv2Data.channel = channelthis.PayChannelv2Data.payPrice = platformPayPricethis.PayChannelv2Data.extOrderInfo = extOrderInfothis.PayChannelv2Data.totalPrice = platformPricethis.PayChannelv2Data.hotelId = hotelIdthis.PayChannelv2Data.roomId = roomIdthis.PayChannelv2Data.checkIn = checkInthis.PayChannelv2Data.checkOut = checkOutthis.PayChannelv2Data.supplierId = supplierIdthis.PayChannelv2Data.snapshotPolices = this.snapshotPolices
}// new
selectPayChannelv2({ productId, channel, platformPayPrice, extOrderInfo, platformPrice, hotelId, roomId, checkIn, checkOut, supplierId }) {this.PayChannelv2Data = {roomId,channel,hotelId,checkIn,checkOut,productId,supplierId,extOrderInfo,payPrice: platformPayPrice,totalPrice: platformPrice,orderId: this.$route.query.orderId,snapshotPolices: this.snapshotPolices}
}
5、展开运算符
...
表示- 展开数组、对象
- 组合数组、对象
// 组合数组
const fruits = ['apples', 'bananas', 'pears']
const vegetables = ['corn', 'potatoes', 'carrots']// old
const produce = fruits.concat(vegetables)
console.log(produce) // ['apples', 'bananas', 'pears', 'corn', 'potatoes', 'carrots']// new
const produce = [...fruits,...vegetables]
console.log(produce) // ['apples', 'bananas', 'pears', 'corn', 'potatoes', 'carrots']
6、箭头函数
- 普通函数可以是函数声明或者函数表达式, 但是箭头函数始终都是表达式, 全程是箭头函数表达式
// old
const upperizedNames = ['Farrin', 'Kagure', 'Asser'].map(function(name) { return name.toUpperCase()
})// new
const upperizedNames = ['Farrin', 'Kagure', 'Asser'].map(name => name.toUpperCase()
)
前端代码优化(持续更新中)相关推荐
- 前端知识点总结——JS高级(持续更新中)
前端知识点总结--JS高级(持续更新中) 1.字符串 什么是: 连续存储多个字符的字符数组 相同: 1. 下标 2. .length 3. 遍历 4. 选取: slice(starti[, endi] ...
- 微信小程序-仿淘宝(附真机测试图)(持续更新中。。。)
醉前端 微信小程序已开始公测, 醉前端 的开发热情依然不减... 这是仿手机淘宝做的微信小程序,目的在于享受开发,学习小程序,欢迎大家批评指正. demo资源地址:demo gihub传送门 tip: ...
- Go语言开发学习笔记(持续更新中)
Go语言开发学习笔记(持续更新中) 仅供自我学习 更好的文档请选择下方 https://studygolang.com/pkgdoc https://www.topgoer.com/go%E5%9F% ...
- JAVA面试大全(持续更新中...)
本文旨在收集Java面试过程中出现的问题,力求全面,仅作学习交流,欢迎补充,持续更新中-,部分段落选取自网上,部分引用文章已标注,部分已记不清了,如侵权,联系本人 Java基础 1.面向对象的概述 面 ...
- 2020年拼多多校招面试题及答案-最全最新-持续更新中(2)
大家好我是好好学习天天编程的天天 一个整天在互联网上种菜和砍柴的程序员~ 2020年拼多多校招面试题及答案-最全最新-持续更新中(2) 2020年拼多多校招面试题一面 2020年拼多多校招面试题一面- ...
- 最好的Vue组件库之Vuetify的入坑指南(持续更新中)
目录 安装Vuetify 文档结构 快速入门 特性 样式和动画 首先先声明,个人不是什么很牛逼的大佬,只是想向那些想入坑Vuetify的前端新手或者嫌文档太长不知如何入手的人提供一些浅显的建议而已,能 ...
- 若依微服务框架ruoyi-cloud使用手册(持续更新中)
若依微服务框架ruoyi-cloud使用手册(持续更新中) 一.项目启动事项 二.新建功能模块案例 三.不同微服务系统间接口调用案例 四.服务器部署 五.一些坑~ 一.项目启动事项 1.首先进行项目相 ...
- 【Vue全家桶+SSR+Koa2全栈开发】项目搭建过程 整合 学习目录(持续更新中)
写在开头 大家好,这里是lionLoveVue,基础知识决定了编程思维,学如逆水行舟,不进则退.金三银四,为了面试也还在慢慢积累知识,Github上面可以直接查看所有前端知识点梳理,github传送门 ...
- Java自学视频整理(持续更新中...)
1.Java基础视频 <张孝祥JAVA视频教程>完整版[RMVB](东西网) 历经5年锤炼(史上最适合初学者入门的Java基础视频)(传智播客) 张孝祥2010年贺岁视频:Java高新技术 ...
- 【计算机英语词汇和词组-持续更新中】
推荐词典:有道词典 理由:在看外文网站的时候,可以实现 取词和划词翻译 这是 在看外文网站的时候,一点点 记录的学习笔记,归纳后方便记忆 按照 首字母顺序排列 备注的发音音标,都是美式的发音 持续更新 ...
最新文章
- CodeSign error: code signing is required for product type Application in SDK iOS XXX的解决办法
- 生物计算论文笔记1:The construction of next-generationmatrices for compartmentalepidemic models
- hihoCoder #1467 : 2-SAT·hihoCoder音乐节
- java在进行修改时报400_java开发注册群组报错400
- 301. Remove Invalid Parentheses
- 德国数字化进展迅速,远程发送诉讼仅需6小时
- app怎么调用mysql数据_数据库: 安装配置数据库,使用Navicat for MySQL和手机APP 连接测试...
- [debug] Expected to have finished reduction in the prior iteration before starting a new one.
- jaxen-1.1-beta-6.jar下载地址
- SMA、SMB、SMC封装的二极管尺寸区分
- 走向ASP.NET架构设计---第二章:设计 测试 代码 (前篇)
- Microsoft Edge浏览器或者电脑上其他浏览器的主页被篡改后的解决办法。(适用于联想电脑)
- openstreetmap_kubernetes中的openstreetmap tile服务器
- linux云主机登陆教程,登录linux云服务器的详情步骤
- 基于51单片机的篮球记分牌设计
- CorelDRAW X7导出pdf发现部分有白边如何处理
- 如何检验计算机主板的好坏,怎么判断笔记本主板、CPU硬件好坏? 查看电脑配置的教程...
- JavaScript高阶
- 2021年危险化学品经营单位安全管理人员模拟试题及危险化学品经营单位安全管理人员实操考试视频
- the selection cannot be run on any server解决方法