没有废话直接上代码👇
?? 非空运算符
x ?? y :如果x不是 null/undefined,将返回x,否则返回y。
let nullVariable = null
let undefinedVariable = undefined
let name = 'beige'
let arr = [{id: 1, type: 'a'}, {id: 2, type: 'b'}]
nullVariable ?? name // => beige
undefinedVariable ?? name // => beige
objVariable.data.length ?? name // => 2
场景1: 封装组件
这个操作符对于封装组件的时候比较好用,很多组件在定义prop的时候就定义了数据的type所以我们封装的组件的时候不能用逻辑&&
disabled
- a: 全局表单存在disable控制优先使用全局
- b: 全局不存在用表单项目的disable
- c: 如果表单项也没有控制disable需要给个默认Boolean值
placeholder
- 全局表单不存在disable才展示表单项的placeholder
Bad
<el-input
:disabled="(globalDisable || item.disabled) || defaultDisable"
:placeholder="!globalDisable ? item.placeholder :''"
>
</el-input>
Good
<el-input
...
:disabled="computedDisable"
:placeholder="isShowPlaceHolder"
>
</el-input>
<script>
computed: {
computedDisable({globalDisable, item = {disabled: false}}) {
return globalDisable ?? item.disabled
},
isShowPlaceHolder({globalDisable, item = {placeholder: ''}}) {
return !globalDisable && placeholder
}
},
</script>
场景2: 条件必传判断
使用@监听表格过滤的查询事件, 控制表格的参数必传
search(params = {}) {
let tip = ''
let isEmpty = {
dateRangeEmpty: '请选择时间范围',
statusEmpty: '请选择状态'
}
switch (true) {
case params['daterange'] ?? '0' === '0':
tip = isEmpty[dateRangeEmpty]
break
case params['status'] ?? '1' === '1':
tip = isEmpty[statusEmpty]
break
}
if (tip) {
return this.$message.error(tip)
}
// 过了校验调就用接口
this.dataTableSearch(params)
}
??= 空赋值运算符
??=跟上面的非空运算符非常相似,x ??= y: 如果x是 null/undefined,将x赋值为y。
let nullVariable = null
let undefinedVariable = undefined
let name = 'beige'
let arr = [{id: 1, type: 'a'}, {id: 2, type: 'b'}]
let youname = nullVariable ??= name
consooe.log(youname) // => 'beige'
// 这两等价
let youname = nullVariable ?? name
consooe.log(youname) // => 'beige'
场景1: 给配置项默认值
function dialogOptions(options) {
options.dialog ??= false
options.title ??= '选择数据'
return options
}
function dialogOptions(dialog = false, title = '选择数据') {
return {dialog, options}
}
gameSettingsWithNullish({dialog: null, title: null}) // => {dialog: false, title: '选择数据'}
gameSettingsWithDefaultParams(undefined, null) // => {gameSpeed: null, gameDiff: null}
?. 链判断运算符
?. 链判断运算符允许读取深度嵌套在对象链中的属性值, 当引用为空时,表达式停止计算并返回 undefined,从而不必验证每个引用
let res = {
data: {
name: 'beige',
list: [{id: '1'}],
projectEntrys: null
}
}
res.data?.projectEntrys.find(i => i.id) // {id: '1'}
res.data?.projectEntrys.find(i => !i.id) // undefined
当我们动态给元素项添加某个标识可以通过链判断来减少冗杂的条件语句
let columns = [ // 初始的数据
{porperty: 'A'},
{porperty: 'B'},
{porperty: 'C'},
]
// 后续不确定里面会push进去多少个
let childrens = [{porperty: 'A'}, ......]
columns.forEach(i => {
childrens.find(i => i.prop === column.property)?.index === index
})
写在最后
如果文章中有那块写的不太好或有问题欢迎大家指出,我也会在后面的文章不停修改。也希望自己进步的同时能跟你们一起成长。喜欢我文章的朋友们也可以关注一下
我会很感激第一批关注我的人。此时,年轻的我和你,轻装上阵;而后,富裕的你和我,满载而归。
往期文章
【前端体系】从一道面试题谈谈对EventLoop的理解(更新了四道进阶题的解析)