前端代码优化(持续更新中)

优化

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 += '日'
      break
    case 1 :
      string += '一'
      break
    case 2 :
      string += '二'
      break
    case 3 :
      string += '三'
      break
    case 4 :
      string += '四'
      break
    case 5 :
      string += '五'
      break
    case 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、过滤器优化

//old

Vue.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] = true
      break
    default:
      this.handleCheckIsEmpty() && (this.hotelIds = this.multipleSelection.join(','), this.handleMoreOperation(command))
      break
  }
}
// 处理必须选中一行操作项
handleMoreOperation(command) {
  switch (command) {
    case 'batchSoldOut':
    case 'batchPutaway':
      this.hotelStandUpDownVisible = true
      this.hotelTitle = command
      break

    case 'joinTags':
    case 'outTags':
      this.joinTagsVisible = true
      this.operatingState = command
      break

    case 'batchChangeSchemeVisible':
    case 'batchJoinGroupVisible':
      this[command] = true
      break

    case 'batchOutGroup':
      this.assignGroup(this.hotelIds, '')
      break

    default:
      break
  }
}

// old
// 锁单
handleOrderLock({ orderId }) {
  this.orderId = orderId
  this.lock()
},
// 确认有房
handleConfirmHaveRoom({ orderId }) {
  this.orderId = orderId
  this.confirm()
},
// 拒单
handleRefusedOrder({ orderId }) {
  this.orderId = orderId
  this.deny()
},
handleConfirmQunarHaveRoom({ orderId }) {
 // 去哪儿游贝、嗨飞情况填写确认信息
 this.orderId = orderId
 this.qunarArrangeRoomVisible = true
},
// 查看酒店信息
handleViewHotelInfo({ hotelId }) {
 this.hotelIds = hotelId
 this.viewHotelInfoVisible = true
},

// new
// 处理操作请求
handleOperation({ orderId }, type) {
  this.orderId = orderId
  this[type]()
},
// 处理组件显示
handleComponentVisible({ hotelId, orderId }, type) {
  this.hotelIds = hotelId
  this.orderId = orderId
  type === '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.orderId
      this.PayChannelv2Data.productId = productId
      this.PayChannelv2Data.channel = channel
      this.PayChannelv2Data.payPrice = platformPayPrice
      this.PayChannelv2Data.extOrderInfo = extOrderInfo
      this.PayChannelv2Data.totalPrice = platformPrice
      this.PayChannelv2Data.hotelId = hotelId
      this.PayChannelv2Data.roomId = roomId
      this.PayChannelv2Data.checkIn = checkIn
      this.PayChannelv2Data.checkOut = checkOut
      this.PayChannelv2Data.supplierId = supplierId
      this.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()
)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值