工作中常用的 ES6 语法

变量声明

let 和const

不用var, 用const声明只读变量,let声明变量。let和const都是块级作用域

const RULE = 'RULE'
let date = new Date()
console.log(date.getTime())

重新给const变量赋值会报错

VM12866:1 Uncaught TypeError: Assignment to constant variable.

模板字符串(template string)

是增强版的字符串,用反引号(`)标识;
可以定义字符串,定义多行文本,也可以在字符串中插入变量

let name = 'ES6'
console.log(`hello ${name}`)
// 多行
let content = `
  Hello ${name},
 you will be more popular, welcome~~
`
console.log(content) // 这里打印出的字符串是带格式的,包括空格和缩进

在实际使用中例子,项目中有个在前端的导出功能。
不用模板字符串的写法

exportTableData () {
    //  导出csv
    let head = '#,客户名称,厂区数量,智能终端数量,所属代理商,所属分公司,所属大区,创建人,创建时间'
    let str = ''
    this.allListData.forEach((element, i) => {
      str += (i + 1) + ',' + element.name + ',' + element.factoryCount + ',' +
        element.carCount + ',' + element.parentAgent.name + ',' +
        element.parentCompany.name + ',' + element.parentRegion.name + ',' +
        element.createUser + ',' + element.createTime + ',' + '\n'
    })
    str = str.replace(/undefined/g, '""') // 处理undefined
    exportCSV('客户档案', head + '\n' + str)
},

用模板字符串后,

exportCSVFile () {
    let fileName = this.currOrg.name + ' - 驾驶员档案'
    let content = '#,驾驶员姓名,手机号,身份证号,QQ号,钥匙卡数量,创建人,创建时间\n'
    this.ftyList.forEach((v, i) => {
      content += `${i + 1},${v.identification},${v.qq},${v.cardCount},${v.createUser},${v.createTime}\n`
    })
    exportCSV(fileName, content)
},

写法立刻就很简单了~~~

默认参数

这个跟php里的默认很像

function log(msg, type = 'log') {
  console.log(msg, type)
}
log('hello')  // hello log

// php
function __construct( $dataLength = 0, $isPrimaryKey = FALSE, $createTime='') {
    parent::__construct();
    $this->dataLength       = intval($dataLength);
    $this->isPrimaryKey     = $isPrimaryKey;
    $this->attributeCreateTime = $createTime;
}

箭头函数

只能说用的太多了~~,一定要能看懂别人的箭头函数,还要自己会写
看了一下之前学的阮一峰的笔记,箭头函数还是有挺多东西可写的,这里举个简单的例子算了。

let arr = [1, 2, 3, 'a', 'b']
arr.forEach((ele, i) => {
  arr[i] = ele + ele
})
console.log(arr)

模块的import 和export

import 用于引入模块,export用于定义模块后导出模块
export 可以对外导出变量,方法,类,
以下是项目中写的实例:

// Sidebar 文件夹下index.js
import Sidebar from './SidebarWrapper'
export default Sidebar

// Sidebar.vue
 export default {
    data () {
      return {
        currentPath: this.$route.path
      }
    }
  }

// Sidebar.vue 在其他文件中被引用
  import Sidebar from './Sidebar'
  export default {
    name: 'SidebarWrapper',
    components: { Sidebar }
  }

另外定义一些公共的js方法的导出

/* 以字母开头 4-20位 大小写字母、数字、下划线 */
export function validateAccount (str) {
  const reg = /^[A-z]\w{3,19}$/
  return reg.test(str)
}

/* 是否邮箱 */
export function validateEmail (str) {
  const reg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
  return reg.test(str.trim())
}

// 在别的文件中引用
import { validateAccount, validateEmail } from '@/utils/validate'

//引入全部作为reducers对象
import * as reduces from './reduces'

ES6对象和数组

解构赋值

// 数组
let [a, b, c] = [1, 2, 3]
// 对象
let {foo, bar} = {foo: 'aaa', bar: 'bbb'}

// 函数的参数使用解构赋值
function add([x, y]){
  return x + y
}
add([1, 2])


// 函数的逐层解析
let x = {
  a: {
    b: 1
  },
  c: 2
}
let counter = ({a: {b}, c}) => b + c
counter(x)

属性的简洁表示法

let foo = 'bar'
let baz = {foo}
// 等同于
let baz = {foo: foo}

//方法也可简写
let o = {
  validateLowerCase (str) {
    const reg = /^[a-z]+$/
    return reg.test(str)
  }
}
// 等同于
let o = {
  validateLowerCase: function(str) {
    const reg = /^[a-z]+$/
    return reg.test(str)
  }
}

扩展运算符

扩展运算符(spread)是三个点(...)。用于取出参数对象的所有可遍历属性,拷贝到当前对象中

const a = [1, 2];
const b = [...a, 3];
console.log(b)

// 代替 apply。
function foo(x, y, z) {}
const args = [1,2,3]

// 下面两句效果相同
foo.apply(null, args)
foo(...args)

// 组装对象

const a = { x : 1, y : 2 }
const b = { ...a, z : 3 }

这个在实际拼装后端请求参数时非常有用,下面是请求实例:
之前写法: 如下,每个参数在接受参数的时候都需要写一遍,调用这个函数时,也需要写一遍,ajax中还需要写一遍,一共写了3遍

function listStock(offset,count,deviceId,beginTime,endTime,activeStatus,subDomain,callback){
        $.ajax({
            type:"post",
            url:"/deviceLic.php",
            data:{
                offset: offset,
                count: count,
                deviceId: deviceId,
                beginTime: beginTime,
                endTime: endTime,
                activeStatus: activeStatus,
                subDomain: subDomain,
                action:'listStock',
            },
            success: function(data){
                
            }
        })
    }
 listStock(offset,count,deviceId,beginTime,endTime,activeStatus,subDomain)

用扩展运算符,写一遍就OK了。

let search = {
  cardId: '',
  terminalId: '',       // 可选,终端编号
  createUser: '',        // 可选,登记人
  startTime: undefined,
  endTime: undefined,
  offset: 0,
  limit: 10
}
function listRepairRecords (search) {
  fetch('listRepairRecords', {
    ...this.search,
    userId: this.userId,
    orgId: this.currOrg.orgId
  })
    .then(res => {
   
    })
    .catch(err => {
   
   })
}
  listRepairRecords (search)

Promise

异步编程的解决方案。
简单说是一个容器,保存着某个未来才会结束的事件(通常是异步操作),从它可以获取异步操作的消息

//基本用法:
var promise = new Promise(function(resolve, reject) {
    //  some code
    if(true /*异步操作成功*/ ) {
        resolve(value);
    } else {
        reject(error);
    }
});

项目中的实例,向后端发起请求

fetch('getMaintainItems', {
  userId: this.userId
})
  .then(res => {
    console.log(res)
  })
  .catch(err => {
    this.$message({
      message: err.error ? err.error : '请求失败,请重试',
      type: 'warning'
    })
  })

你可能感兴趣的:(工作中常用的 ES6 语法)